Debian Codegraph @

tpl/internal/go_templates/htmltemplate/template.go

raw
1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package template
6
7 import (
8 "fmt"
9 "io"
10 "io/fs"
11 "os"
12 "path"
13 "path/filepath"
14 "sync"
15
16 template "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate"
17 "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse"
18 )
19
20 // Template is a specialized Template from "text/template" that produces a safe
21 // HTML document fragment.
22 type Template struct {
23 // Sticky error if escaping fails, or escapeOK if succeeded.
24 escapeErr error
25 // We could embed the text/template field, but it's safer not to because
26 // we need to keep our version of the name space and the underlying
27 // template's in sync.
28 text *template.Template
29 // The underlying template's parse tree, updated to be HTML-safe
30 // after the first execution.
31 Tree *parse.Tree
32 *nameSpace // common to all associated templates
33 }
34
35 // escapeOK is a sentinel value used to indicate valid escaping.
36 var escapeOK = fmt.Errorf("template escaped correctly")
37
38 // nameSpace is the data structure shared by all templates in an association.
39 type nameSpace struct {
40 mu sync.Mutex
41 set map[string]*Template
42 escaped bool
43 esc escaper
44 }
45
46 // Templates returns a slice of the templates associated with t, including t
47 // itself.
48 func (t *Template) Templates() []*Template {
49 ns := t.nameSpace
50 ns.mu.Lock()
51 defer ns.mu.Unlock()
52 // Return a slice so we don't expose the map.
53 m := make([]*Template, 0, len(ns.set))
54 for _, v := range ns.set {
55 m = append(m, v)
56 }
57 return m
58 }
59
60 // Option sets options for the template. Options are described by
61 // strings, either a simple string or "key=value". There can be at
62 // most one equals sign in an option string. If the option string
63 // is unrecognized or otherwise invalid, Option panics.
64 //
65 // Known options:
66 //
67 // missingkey: Control the behavior during execution if a map is
68 // indexed with a key that is not present in the map.
69 //
70 // "missingkey=default" or "missingkey=invalid"
71 // The default behavior: Do nothing and continue execution.
72 // If printed, the result of the index operation is the string
73 // "<no value>".
74 // "missingkey=zero"
75 // The operation returns the zero value for the map type's element.
76 // "missingkey=error"
77 // Execution stops immediately with an error.
78 func (t *Template) Option(opt ...string) *Template {
79 t.text.Option(opt...)
80 return t
81 }
82
83 // checkCanParse checks whether it is OK to parse templates.
84 // If not, it returns an error.
85 func (t *Template) checkCanParse() error {
86 if t == nil {
87 return nil
88 }
89 t.nameSpace.mu.Lock()
90 defer t.nameSpace.mu.Unlock()
91 if t.nameSpace.escaped {
92 return fmt.Errorf("html/template: cannot Parse after Execute")
93 }
94 return nil
95 }
96
97 // escape escapes all associated templates.
98 func (t *Template) escape() error {
99 t.nameSpace.mu.Lock()
100 defer t.nameSpace.mu.Unlock()
101 t.nameSpace.escaped = true
102 if t.escapeErr == nil {
103 if t.Tree == nil {
104 return fmt.Errorf("template: %q is an incomplete or empty template", t.Name())
105 }
106 if err := escapeTemplate(t, t.text.Root, t.Name()); err != nil {
107 return err
108 }
109 } else if t.escapeErr != escapeOK {
110 return t.escapeErr
111 }
112 return nil
113 }
114
115 // Execute applies a parsed template to the specified data object,
116 // writing the output to wr.
117 // If an error occurs executing the template or writing its output,
118 // execution stops, but partial results may already have been written to
119 // the output writer.
120 // A template may be executed safely in parallel, although if parallel
121 // executions share a Writer the output may be interleaved.
122 func (t *Template) Execute(wr io.Writer, data any) error {
123 if err := t.escape(); err != nil {
124 return err
125 }
126 return t.text.Execute(wr, data)
127 }
128
129 // ExecuteTemplate applies the template associated with t that has the given
130 // name to the specified data object and writes the output to wr.
131 // If an error occurs executing the template or writing its output,
132 // execution stops, but partial results may already have been written to
133 // the output writer.
134 // A template may be executed safely in parallel, although if parallel
135 // executions share a Writer the output may be interleaved.
136 func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error {
137 tmpl, err := t.lookupAndEscapeTemplate(name)
138 if err != nil {
139 return err
140 }
141 return tmpl.text.Execute(wr, data)
142 }
143
144 // lookupAndEscapeTemplate guarantees that the template with the given name
145 // is escaped, or returns an error if it cannot be. It returns the named
146 // template.
147 func (t *Template) lookupAndEscapeTemplate(name string) (tmpl *Template, err error) {
148 t.nameSpace.mu.Lock()
149 defer t.nameSpace.mu.Unlock()
150 t.nameSpace.escaped = true
151 tmpl = t.set[name]
152 if tmpl == nil {
153 return nil, fmt.Errorf("html/template: %q is undefined", name)
154 }
155 if tmpl.escapeErr != nil && tmpl.escapeErr != escapeOK {
156 return nil, tmpl.escapeErr
157 }
158 if tmpl.text.Tree == nil || tmpl.text.Root == nil {
159 return nil, fmt.Errorf("html/template: %q is an incomplete template", name)
160 }
161 if t.text.Lookup(name) == nil {
162 panic("html/template internal error: template escaping out of sync")
163 }
164 if tmpl.escapeErr == nil {
165 err = escapeTemplate(tmpl, tmpl.text.Root, name)
166 }
167 return tmpl, err
168 }
169
170 // DefinedTemplates returns a string listing the defined templates,
171 // prefixed by the string "; defined templates are: ". If there are none,
172 // it returns the empty string. Used to generate an error message.
173 func (t *Template) DefinedTemplates() string {
174 return t.text.DefinedTemplates()
175 }
176
177 // Parse parses text as a template body for t.
178 // Named template definitions ({{define ...}} or {{block ...}} statements) in text
179 // define additional templates associated with t and are removed from the
180 // definition of t itself.
181 //
182 // Templates can be redefined in successive calls to Parse,
183 // before the first use of [Template.Execute] on t or any associated template.
184 // A template definition with a body containing only white space and comments
185 // is considered empty and will not replace an existing template's body.
186 // This allows using Parse to add new named template definitions without
187 // overwriting the main template body.
188 func (t *Template) Parse(text string) (*Template, error) {
189 if err := t.checkCanParse(); err != nil {
190 return nil, err
191 }
192
193 ret, err := t.text.Parse(text)
194 if err != nil {
195 return nil, err
196 }
197
198 // In general, all the named templates might have changed underfoot.
199 // Regardless, some new ones may have been defined.
200 // The template.Template set has been updated; update ours.
201 t.nameSpace.mu.Lock()
202 defer t.nameSpace.mu.Unlock()
203 for _, v := range ret.Templates() {
204 name := v.Name()
205 tmpl := t.set[name]
206 if tmpl == nil {
207 tmpl = t.new(name)
208 }
209 tmpl.text = v
210 tmpl.Tree = v.Tree
211 }
212 return t, nil
213 }
214
215 // AddParseTree creates a new template with the name and parse tree
216 // and associates it with t.
217 //
218 // It returns an error if t or any associated template has already been executed.
219 func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error) {
220 if err := t.checkCanParse(); err != nil {
221 return nil, err
222 }
223
224 t.nameSpace.mu.Lock()
225 defer t.nameSpace.mu.Unlock()
226 text, err := t.text.AddParseTree(name, tree)
227 if err != nil {
228 return nil, err
229 }
230 ret := &Template{
231 nil,
232 text,
233 text.Tree,
234 t.nameSpace,
235 }
236 t.set[name] = ret
237 return ret, nil
238 }
239
240 // Clone returns a duplicate of the template, including all associated
241 // templates. The actual representation is not copied, but the name space of
242 // associated templates is, so further calls to [Template.Parse] in the copy will add
243 // templates to the copy but not to the original. [Template.Clone] can be used to prepare
244 // common templates and use them with variant definitions for other templates
245 // by adding the variants after the clone is made.
246 //
247 // It returns an error if t has already been executed.
248 func (t *Template) Clone() (*Template, error) {
249 t.nameSpace.mu.Lock()
250 defer t.nameSpace.mu.Unlock()
251 if t.escapeErr != nil {
252 return nil, fmt.Errorf("html/template: cannot Clone %q after it has executed", t.Name())
253 }
254 textClone, err := t.text.Clone()
255 if err != nil {
256 return nil, err
257 }
258 ns := &nameSpace{set: make(map[string]*Template)}
259 ns.esc = makeEscaper(ns)
260 ret := &Template{
261 nil,
262 textClone,
263 textClone.Tree,
264 ns,
265 }
266 ret.set[ret.Name()] = ret
267 for _, x := range textClone.Templates() {
268 name := x.Name()
269 src := t.set[name]
270 if src == nil || src.escapeErr != nil {
271 return nil, fmt.Errorf("html/template: cannot Clone %q after it has executed", t.Name())
272 }
273 x.Tree = x.Tree.Copy()
274 ret.set[name] = &Template{
275 nil,
276 x,
277 x.Tree,
278 ret.nameSpace,
279 }
280 }
281 // Return the template associated with the name of this template.
282 return ret.set[ret.Name()], nil
283 }
284
285 // New allocates a new HTML template with the given name.
286 func New(name string) *Template {
287 ns := &nameSpace{set: make(map[string]*Template)}
288 ns.esc = makeEscaper(ns)
289 tmpl := &Template{
290 nil,
291 template.New(name),
292 nil,
293 ns,
294 }
295 tmpl.set[name] = tmpl
296 return tmpl
297 }
298
299 // New allocates a new HTML template associated with the given one
300 // and with the same delimiters. The association, which is transitive,
301 // allows one template to invoke another with a {{template}} action.
302 //
303 // If a template with the given name already exists, the new HTML template
304 // will replace it. The existing template will be reset and disassociated with
305 // t.
306 func (t *Template) New(name string) *Template {
307 t.nameSpace.mu.Lock()
308 defer t.nameSpace.mu.Unlock()
309 return t.new(name)
310 }
311
312 // new is the implementation of New, without the lock.
313 func (t *Template) new(name string) *Template {
314 tmpl := &Template{
315 nil,
316 t.text.New(name),
317 nil,
318 t.nameSpace,
319 }
320 if existing, ok := tmpl.set[name]; ok {
321 emptyTmpl := New(existing.Name())
322 *existing = *emptyTmpl
323 }
324 tmpl.set[name] = tmpl
325 return tmpl
326 }
327
328 // Name returns the name of the template.
329 func (t *Template) Name() string {
330 return t.text.Name()
331 }
332
333 type FuncMap = template.FuncMap
334
335 // Funcs adds the elements of the argument map to the template's function map.
336 // Any function used in the template must be added before the template is
337 // parsed. Funcs may be called more than once, including after parsing (for
338 // example, after [Template.Clone]), to replace a function of the same name;
339 // the replacement is used when the template is executed.
340 // It panics if a value in the map is not a function with appropriate return
341 // type. The return value is the template, so calls can be chained.
342 func (t *Template) Funcs(funcMap FuncMap) *Template {
343 t.text.Funcs(template.FuncMap(funcMap))
344 return t
345 }
346
347 // Delims sets the action delimiters to the specified strings, to be used in
348 // subsequent calls to [Template.Parse], [ParseFiles], or [ParseGlob]. Nested template
349 // definitions will inherit the settings. An empty delimiter stands for the
350 // corresponding default: {{ or }}.
351 // The return value is the template, so calls can be chained.
352 func (t *Template) Delims(left, right string) *Template {
353 t.text.Delims(left, right)
354 return t
355 }
356
357 // Lookup returns the template with the given name that is associated with t,
358 // or nil if there is no such template.
359 func (t *Template) Lookup(name string) *Template {
360 t.nameSpace.mu.Lock()
361 defer t.nameSpace.mu.Unlock()
362 return t.set[name]
363 }
364
365 // Must is a helper that wraps a call to a function returning ([*Template], error)
366 // and panics if the error is non-nil. It is intended for use in variable initializations
367 // such as
368 //
369 // var t = template.Must(template.New("name").Parse("html"))
370 func Must(t *Template, err error) *Template {
371 if err != nil {
372 panic(err)
373 }
374 return t
375 }
376
377 // ParseFiles creates a new [Template] and parses the template definitions from
378 // the named files. The returned template's name will have the (base) name and
379 // (parsed) contents of the first file. There must be at least one file.
380 // If an error occurs, parsing stops and the returned [*Template] is nil.
381 //
382 // When parsing multiple files with the same name in different directories,
383 // the last one mentioned will be the one that results.
384 // For instance, ParseFiles("a/foo", "b/foo") stores "b/foo" as the template
385 // named "foo", while "a/foo" is unavailable.
386 func ParseFiles(filenames ...string) (*Template, error) {
387 return parseFiles(nil, readFileOS, filenames...)
388 }
389
390 // ParseFiles parses the named files and associates the resulting templates with
391 // t. If an error occurs, parsing stops and the returned template is nil;
392 // otherwise it is t. There must be at least one file.
393 //
394 // When parsing multiple files with the same name in different directories,
395 // the last one mentioned will be the one that results.
396 //
397 // ParseFiles returns an error if t or any associated template has already been executed.
398 func (t *Template) ParseFiles(filenames ...string) (*Template, error) {
399 return parseFiles(t, readFileOS, filenames...)
400 }
401
402 // parseFiles is the helper for the method and function. If the argument
403 // template is nil, it is created from the first file.
404 func parseFiles(t *Template, readFile func(string) (string, []byte, error), filenames ...string) (*Template, error) {
405 if err := t.checkCanParse(); err != nil {
406 return nil, err
407 }
408
409 if len(filenames) == 0 {
410 // Not really a problem, but be consistent.
411 return nil, fmt.Errorf("html/template: no files named in call to ParseFiles")
412 }
413 for _, filename := range filenames {
414 name, b, err := readFile(filename)
415 if err != nil {
416 return nil, err
417 }
418 s := string(b)
419 // First template becomes return value if not already defined,
420 // and we use that one for subsequent New calls to associate
421 // all the templates together. Also, if this file has the same name
422 // as t, this file becomes the contents of t, so
423 // t, err := New(name).Funcs(xxx).ParseFiles(name)
424 // works. Otherwise we create a new template associated with t.
425 var tmpl *Template
426 if t == nil {
427 t = New(name)
428 }
429 if name == t.Name() {
430 tmpl = t
431 } else {
432 tmpl = t.New(name)
433 }
434 _, err = tmpl.Parse(s)
435 if err != nil {
436 return nil, err
437 }
438 }
439 return t, nil
440 }
441
442 // ParseGlob creates a new [Template] and parses the template definitions from
443 // the files identified by the pattern. The files are matched according to the
444 // semantics of filepath.Match, and the pattern must match at least one file.
445 // The returned template will have the (base) name and (parsed) contents of the
446 // first file matched by the pattern. ParseGlob is equivalent to calling
447 // [ParseFiles] with the list of files matched by the pattern.
448 //
449 // When parsing multiple files with the same name in different directories,
450 // the last one mentioned will be the one that results.
451 func ParseGlob(pattern string) (*Template, error) {
452 return parseGlob(nil, pattern)
453 }
454
455 // ParseGlob parses the template definitions in the files identified by the
456 // pattern and associates the resulting templates with t. The files are matched
457 // according to the semantics of filepath.Match, and the pattern must match at
458 // least one file. ParseGlob is equivalent to calling t.ParseFiles with the
459 // list of files matched by the pattern.
460 //
461 // When parsing multiple files with the same name in different directories,
462 // the last one mentioned will be the one that results.
463 //
464 // ParseGlob returns an error if t or any associated template has already been executed.
465 func (t *Template) ParseGlob(pattern string) (*Template, error) {
466 return parseGlob(t, pattern)
467 }
468
469 // parseGlob is the implementation of the function and method ParseGlob.
470 func parseGlob(t *Template, pattern string) (*Template, error) {
471 if err := t.checkCanParse(); err != nil {
472 return nil, err
473 }
474 filenames, err := filepath.Glob(pattern)
475 if err != nil {
476 return nil, err
477 }
478 if len(filenames) == 0 {
479 return nil, fmt.Errorf("html/template: pattern matches no files: %#q", pattern)
480 }
481 return parseFiles(t, readFileOS, filenames...)
482 }
483
484 // IsTrue reports whether the value is 'true', in the sense of not the zero of its type,
485 // and whether the value has a meaningful truth value. This is the definition of
486 // truth used by if and other such actions.
487 func IsTrue(val any) (truth, ok bool) {
488 return template.IsTrue(val)
489 }
490
491 // ParseFS is like [ParseFiles] or [ParseGlob] but reads from the file system fs
492 // instead of the host operating system's file system.
493 // It accepts a list of glob patterns.
494 // (Note that most file names serve as glob patterns matching only themselves.)
495 func ParseFS(fs fs.FS, patterns ...string) (*Template, error) {
496 return parseFS(nil, fs, patterns)
497 }
498
499 // ParseFS is like [Template.ParseFiles] or [Template.ParseGlob] but reads from the file system fs
500 // instead of the host operating system's file system.
501 // It accepts a list of glob patterns.
502 // (Note that most file names serve as glob patterns matching only themselves.)
503 func (t *Template) ParseFS(fs fs.FS, patterns ...string) (*Template, error) {
504 return parseFS(t, fs, patterns)
505 }
506
507 func parseFS(t *Template, fsys fs.FS, patterns []string) (*Template, error) {
508 var filenames []string
509 for _, pattern := range patterns {
510 list, err := fs.Glob(fsys, pattern)
511 if err != nil {
512 return nil, err
513 }
514 if len(list) == 0 {
515 return nil, fmt.Errorf("template: pattern matches no files: %#q", pattern)
516 }
517 filenames = append(filenames, list...)
518 }
519 return parseFiles(t, readFileFS(fsys), filenames...)
520 }
521
522 func readFileOS(file string) (name string, b []byte, err error) {
523 name = filepath.Base(file)
524 b, err = os.ReadFile(file)
525 return
526 }
527
528 func readFileFS(fsys fs.FS) func(string) (string, []byte, error) {
529 return func(file string) (name string, b []byte, err error) {
530 name = path.Base(file)
531 b, err = fs.ReadFile(fsys, file)
532 return
533 }
534 }