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 // Execute applies a parsed template to the specified data object,
49 // writing the output to wr.
50 func (t *Template) Execute(wr io.Writer, data interface{}) (err error) {
53 if err = escapeTemplates(t, t.Name()); err != nil {
57 t.nameSpace.mu.Unlock()
61 return t.text.Execute(wr, data)
64 // ExecuteTemplate applies the template associated with t that has the given
65 // name to the specified data object and writes the output to wr.
66 func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
67 tmpl, err := t.lookupAndEscapeTemplate(name)
71 return tmpl.text.Execute(wr, data)
74 // lookupAndEscapeTemplate guarantees that the template with the given name
75 // is escaped, or returns an error if it cannot be. It returns the named
77 func (t *Template) lookupAndEscapeTemplate(name string) (tmpl *Template, err error) {
79 defer t.nameSpace.mu.Unlock()
82 return nil, fmt.Errorf("html/template: %q is undefined", name)
84 if tmpl.text.Tree == nil || tmpl.text.Root == nil {
85 return nil, fmt.Errorf("html/template: %q is an incomplete template", name)
87 if t.text.Lookup(name) == nil {
88 panic("html/template internal error: template escaping out of sync")
90 if tmpl != nil && !tmpl.escaped {
91 err = escapeTemplates(tmpl, name)
96 // Parse parses a string into a template. Nested template definitions
97 // will be associated with the top-level template t. Parse may be
98 // called multiple times to parse definitions of templates to associate
99 // with t. It is an error if a resulting template is non-empty (contains
100 // content other than template definitions) and would replace a
101 // non-empty template with the same name. (In multiple calls to Parse
102 // with the same receiver template, only one call can contain text
103 // other than space, comments, and template definitions.)
104 func (t *Template) Parse(src string) (*Template, error) {
105 t.nameSpace.mu.Lock()
107 t.nameSpace.mu.Unlock()
108 ret, err := t.text.Parse(src)
112 // In general, all the named templates might have changed underfoot.
113 // Regardless, some new ones may have been defined.
114 // The template.Template set has been updated; update ours.
115 t.nameSpace.mu.Lock()
116 defer t.nameSpace.mu.Unlock()
117 for _, v := range ret.Templates() {
129 // AddParseTree creates a new template with the name and parse tree
130 // and associates it with t.
132 // It returns an error if t has already been executed.
133 func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error) {
134 t.nameSpace.mu.Lock()
135 defer t.nameSpace.mu.Unlock()
137 return nil, fmt.Errorf("html/template: cannot AddParseTree to %q after it has executed", t.Name())
139 text, err := t.text.AddParseTree(name, tree)
152 // Clone returns a duplicate of the template, including all associated
153 // templates. The actual representation is not copied, but the name space of
154 // associated templates is, so further calls to Parse in the copy will add
155 // templates to the copy but not to the original. Clone can be used to prepare
156 // common templates and use them with variant definitions for other templates
157 // by adding the variants after the clone is made.
159 // It returns an error if t has already been executed.
160 func (t *Template) Clone() (*Template, error) {
161 t.nameSpace.mu.Lock()
162 defer t.nameSpace.mu.Unlock()
164 return nil, fmt.Errorf("html/template: cannot Clone %q after it has executed", t.Name())
166 textClone, err := t.text.Clone()
174 set: make(map[string]*Template),
177 for _, x := range textClone.Templates() {
180 if src == nil || src.escaped {
181 return nil, fmt.Errorf("html/template: cannot Clone %q after it has executed", t.Name())
184 x.Tree = &parse.Tree{
186 Root: x.Tree.Root.CopyList(),
189 ret.set[name] = &Template{
198 // New allocates a new HTML template with the given name.
199 func New(name string) *Template {
204 set: make(map[string]*Template),
207 tmpl.set[name] = tmpl
211 // New allocates a new HTML template associated with the given one
212 // and with the same delimiters. The association, which is transitive,
213 // allows one template to invoke another with a {{template}} action.
214 func (t *Template) New(name string) *Template {
215 t.nameSpace.mu.Lock()
216 defer t.nameSpace.mu.Unlock()
220 // new is the implementation of New, without the lock.
221 func (t *Template) new(name string) *Template {
227 tmpl.set[name] = tmpl
231 // Name returns the name of the template.
232 func (t *Template) Name() string {
236 // FuncMap is the type of the map defining the mapping from names to
237 // functions. Each function must have either a single return value, or two
238 // return values of which the second has type error. In that case, if the
239 // second (error) argument evaluates to non-nil during execution, execution
240 // terminates and Execute returns that error. FuncMap has the same base type
241 // as FuncMap in "text/template", copied here so clients need not import
243 type FuncMap map[string]interface{}
245 // Funcs adds the elements of the argument map to the template's function map.
246 // It panics if a value in the map is not a function with appropriate return
247 // type. However, it is legal to overwrite elements of the map. The return
248 // value is the template, so calls can be chained.
249 func (t *Template) Funcs(funcMap FuncMap) *Template {
250 t.text.Funcs(template.FuncMap(funcMap))
254 // Delims sets the action delimiters to the specified strings, to be used in
255 // subsequent calls to Parse, ParseFiles, or ParseGlob. Nested template
256 // definitions will inherit the settings. An empty delimiter stands for the
257 // corresponding default: {{ or }}.
258 // The return value is the template, so calls can be chained.
259 func (t *Template) Delims(left, right string) *Template {
260 t.text.Delims(left, right)
264 // Lookup returns the template with the given name that is associated with t,
265 // or nil if there is no such template.
266 func (t *Template) Lookup(name string) *Template {
267 t.nameSpace.mu.Lock()
268 defer t.nameSpace.mu.Unlock()
272 // Must is a helper that wraps a call to a function returning (*Template, error)
273 // and panics if the error is non-nil. It is intended for use in variable initializations
275 // var t = template.Must(template.New("name").Parse("html"))
276 func Must(t *Template, err error) *Template {
283 // ParseFiles creates a new Template and parses the template definitions from
284 // the named files. The returned template's name will have the (base) name and
285 // (parsed) contents of the first file. There must be at least one file.
286 // If an error occurs, parsing stops and the returned *Template is nil.
287 func ParseFiles(filenames ...string) (*Template, error) {
288 return parseFiles(nil, filenames...)
291 // ParseFiles parses the named files and associates the resulting templates with
292 // t. If an error occurs, parsing stops and the returned template is nil;
293 // otherwise it is t. There must be at least one file.
294 func (t *Template) ParseFiles(filenames ...string) (*Template, error) {
295 return parseFiles(t, filenames...)
298 // parseFiles is the helper for the method and function. If the argument
299 // template is nil, it is created from the first file.
300 func parseFiles(t *Template, filenames ...string) (*Template, error) {
301 if len(filenames) == 0 {
302 // Not really a problem, but be consistent.
303 return nil, fmt.Errorf("html/template: no files named in call to ParseFiles")
305 for _, filename := range filenames {
306 b, err := ioutil.ReadFile(filename)
311 name := filepath.Base(filename)
312 // First template becomes return value if not already defined,
313 // and we use that one for subsequent New calls to associate
314 // all the templates together. Also, if this file has the same name
315 // as t, this file becomes the contents of t, so
316 // t, err := New(name).Funcs(xxx).ParseFiles(name)
317 // works. Otherwise we create a new template associated with t.
322 if name == t.Name() {
327 _, err = tmpl.Parse(s)
335 // ParseGlob creates a new Template and parses the template definitions from the
336 // files identified by the pattern, which must match at least one file. The
337 // returned template will have the (base) name and (parsed) contents of the
338 // first file matched by the pattern. ParseGlob is equivalent to calling
339 // ParseFiles with the list of files matched by the pattern.
340 func ParseGlob(pattern string) (*Template, error) {
341 return parseGlob(nil, pattern)
344 // ParseGlob parses the template definitions in the files identified by the
345 // pattern and associates the resulting templates with t. The pattern is
346 // processed by filepath.Glob and must match at least one file. ParseGlob is
347 // equivalent to calling t.ParseFiles with the list of files matched by the
349 func (t *Template) ParseGlob(pattern string) (*Template, error) {
350 return parseGlob(t, pattern)
353 // parseGlob is the implementation of the function and method ParseGlob.
354 func parseGlob(t *Template, pattern string) (*Template, error) {
355 filenames, err := filepath.Glob(pattern)
359 if len(filenames) == 0 {
360 return nil, fmt.Errorf("html/template: pattern matches no files: %#q", pattern)
362 return parseFiles(t, filenames...)