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.
17 // Template is a specialized Template from "text/template" that produces a safe
18 // HTML document fragment.
19 type Template struct {
21 // We could embed the text/template field, but it's safer not to because
22 // we need to keep our version of the name space and the underlying
23 // template's in sync.
24 text *template.Template
25 *nameSpace // common to all associated templates
28 // nameSpace is the data structure shared by all templates in an association.
29 type nameSpace struct {
31 set map[string]*Template
34 // Templates returns a slice of the templates associated with t, including t
36 func (t *Template) Templates() []*Template {
40 // Return a slice so we don't expose the map.
41 m := make([]*Template, 0, len(ns.set))
42 for _, v := range ns.set {
48 // escape escapes all associated templates.
49 func (t *Template) escape() error {
51 defer t.nameSpace.mu.Unlock()
53 if err := escapeTemplates(t, t.Name()); err != nil {
61 // Execute applies a parsed template to the specified data object,
62 // writing the output to wr.
63 func (t *Template) Execute(wr io.Writer, data interface{}) error {
64 if err := t.escape(); err != nil {
67 return t.text.Execute(wr, data)
70 // ExecuteTemplate applies the template associated with t that has the given
71 // name to the specified data object and writes the output to wr.
72 func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
73 tmpl, err := t.lookupAndEscapeTemplate(name)
77 return tmpl.text.Execute(wr, data)
80 // lookupAndEscapeTemplate guarantees that the template with the given name
81 // is escaped, or returns an error if it cannot be. It returns the named
83 func (t *Template) lookupAndEscapeTemplate(name string) (tmpl *Template, err error) {
85 defer t.nameSpace.mu.Unlock()
88 return nil, fmt.Errorf("html/template: %q is undefined", name)
90 if tmpl.text.Tree == nil || tmpl.text.Root == nil {
91 return nil, fmt.Errorf("html/template: %q is an incomplete template", name)
93 if t.text.Lookup(name) == nil {
94 panic("html/template internal error: template escaping out of sync")
96 if tmpl != nil && !tmpl.escaped {
97 err = escapeTemplates(tmpl, name)
102 // Parse parses a string into a template. Nested template definitions
103 // will be associated with the top-level template t. Parse may be
104 // called multiple times to parse definitions of templates to associate
105 // with t. It is an error if a resulting template is non-empty (contains
106 // content other than template definitions) and would replace a
107 // non-empty template with the same name. (In multiple calls to Parse
108 // with the same receiver template, only one call can contain text
109 // other than space, comments, and template definitions.)
110 func (t *Template) Parse(src string) (*Template, error) {
111 t.nameSpace.mu.Lock()
113 t.nameSpace.mu.Unlock()
114 ret, err := t.text.Parse(src)
118 // In general, all the named templates might have changed underfoot.
119 // Regardless, some new ones may have been defined.
120 // The template.Template set has been updated; update ours.
121 t.nameSpace.mu.Lock()
122 defer t.nameSpace.mu.Unlock()
123 for _, v := range ret.Templates() {
135 // AddParseTree creates a new template with the name and parse tree
136 // and associates it with t.
138 // It returns an error if t has already been executed.
139 func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error) {
140 t.nameSpace.mu.Lock()
141 defer t.nameSpace.mu.Unlock()
143 return nil, fmt.Errorf("html/template: cannot AddParseTree to %q after it has executed", t.Name())
145 text, err := t.text.AddParseTree(name, tree)
158 // Clone returns a duplicate of the template, including all associated
159 // templates. The actual representation is not copied, but the name space of
160 // associated templates is, so further calls to Parse in the copy will add
161 // templates to the copy but not to the original. Clone can be used to prepare
162 // common templates and use them with variant definitions for other templates
163 // by adding the variants after the clone is made.
165 // It returns an error if t has already been executed.
166 func (t *Template) Clone() (*Template, error) {
167 t.nameSpace.mu.Lock()
168 defer t.nameSpace.mu.Unlock()
170 return nil, fmt.Errorf("html/template: cannot Clone %q after it has executed", t.Name())
172 textClone, err := t.text.Clone()
180 set: make(map[string]*Template),
183 for _, x := range textClone.Templates() {
186 if src == nil || src.escaped {
187 return nil, fmt.Errorf("html/template: cannot Clone %q after it has executed", t.Name())
190 x.Tree = &parse.Tree{
192 Root: x.Tree.Root.CopyList(),
195 ret.set[name] = &Template{
204 // New allocates a new HTML template with the given name.
205 func New(name string) *Template {
210 set: make(map[string]*Template),
213 tmpl.set[name] = tmpl
217 // New allocates a new HTML template associated with the given one
218 // and with the same delimiters. The association, which is transitive,
219 // allows one template to invoke another with a {{template}} action.
220 func (t *Template) New(name string) *Template {
221 t.nameSpace.mu.Lock()
222 defer t.nameSpace.mu.Unlock()
226 // new is the implementation of New, without the lock.
227 func (t *Template) new(name string) *Template {
233 tmpl.set[name] = tmpl
237 // Name returns the name of the template.
238 func (t *Template) Name() string {
242 // FuncMap is the type of the map defining the mapping from names to
243 // functions. Each function must have either a single return value, or two
244 // return values of which the second has type error. In that case, if the
245 // second (error) argument evaluates to non-nil during execution, execution
246 // terminates and Execute returns that error. FuncMap has the same base type
247 // as FuncMap in "text/template", copied here so clients need not import
249 type FuncMap map[string]interface{}
251 // Funcs adds the elements of the argument map to the template's function map.
252 // It panics if a value in the map is not a function with appropriate return
253 // type. However, it is legal to overwrite elements of the map. The return
254 // value is the template, so calls can be chained.
255 func (t *Template) Funcs(funcMap FuncMap) *Template {
256 t.text.Funcs(template.FuncMap(funcMap))
260 // Delims sets the action delimiters to the specified strings, to be used in
261 // subsequent calls to Parse, ParseFiles, or ParseGlob. Nested template
262 // definitions will inherit the settings. An empty delimiter stands for the
263 // corresponding default: {{ or }}.
264 // The return value is the template, so calls can be chained.
265 func (t *Template) Delims(left, right string) *Template {
266 t.text.Delims(left, right)
270 // Lookup returns the template with the given name that is associated with t,
271 // or nil if there is no such template.
272 func (t *Template) Lookup(name string) *Template {
273 t.nameSpace.mu.Lock()
274 defer t.nameSpace.mu.Unlock()
278 // Must is a helper that wraps a call to a function returning (*Template, error)
279 // and panics if the error is non-nil. It is intended for use in variable initializations
281 // var t = template.Must(template.New("name").Parse("html"))
282 func Must(t *Template, err error) *Template {
289 // ParseFiles creates a new Template and parses the template definitions from
290 // the named files. The returned template's name will have the (base) name and
291 // (parsed) contents of the first file. There must be at least one file.
292 // If an error occurs, parsing stops and the returned *Template is nil.
293 func ParseFiles(filenames ...string) (*Template, error) {
294 return parseFiles(nil, filenames...)
297 // ParseFiles parses the named files and associates the resulting templates with
298 // t. If an error occurs, parsing stops and the returned template is nil;
299 // otherwise it is t. There must be at least one file.
300 func (t *Template) ParseFiles(filenames ...string) (*Template, error) {
301 return parseFiles(t, filenames...)
304 // parseFiles is the helper for the method and function. If the argument
305 // template is nil, it is created from the first file.
306 func parseFiles(t *Template, filenames ...string) (*Template, error) {
307 if len(filenames) == 0 {
308 // Not really a problem, but be consistent.
309 return nil, fmt.Errorf("html/template: no files named in call to ParseFiles")
311 for _, filename := range filenames {
312 b, err := ioutil.ReadFile(filename)
317 name := filepath.Base(filename)
318 // First template becomes return value if not already defined,
319 // and we use that one for subsequent New calls to associate
320 // all the templates together. Also, if this file has the same name
321 // as t, this file becomes the contents of t, so
322 // t, err := New(name).Funcs(xxx).ParseFiles(name)
323 // works. Otherwise we create a new template associated with t.
328 if name == t.Name() {
333 _, err = tmpl.Parse(s)
341 // ParseGlob creates a new Template and parses the template definitions from the
342 // files identified by the pattern, which must match at least one file. The
343 // returned template will have the (base) name and (parsed) contents of the
344 // first file matched by the pattern. ParseGlob is equivalent to calling
345 // ParseFiles with the list of files matched by the pattern.
346 func ParseGlob(pattern string) (*Template, error) {
347 return parseGlob(nil, pattern)
350 // ParseGlob parses the template definitions in the files identified by the
351 // pattern and associates the resulting templates with t. The pattern is
352 // processed by filepath.Glob and must match at least one file. ParseGlob is
353 // equivalent to calling t.ParseFiles with the list of files matched by the
355 func (t *Template) ParseGlob(pattern string) (*Template, error) {
356 return parseGlob(t, pattern)
359 // parseGlob is the implementation of the function and method ParseGlob.
360 func parseGlob(t *Template, pattern string) (*Template, error) {
361 filenames, err := filepath.Glob(pattern)
365 if len(filenames) == 0 {
366 return nil, fmt.Errorf("html/template: pattern matches no files: %#q", pattern)
368 return parseFiles(t, filenames...)