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.Template that produces a safe HTML
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 // Execute applies a parsed template to the specified data object,
35 // writing the output to wr.
36 func (t *Template) Execute(wr io.Writer, data interface{}) (err error) {
39 if err = escapeTemplates(t, t.Name()); err != nil {
43 t.nameSpace.mu.Unlock()
47 return t.text.Execute(wr, data)
50 // ExecuteTemplate applies the template associated with t that has the given
51 // name to the specified data object and writes the output to wr.
52 func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) (err error) {
55 if (tmpl == nil) != (t.text.Lookup(name) == nil) {
56 panic("html/template internal error: template escaping out of sync")
58 if tmpl != nil && !tmpl.escaped {
59 err = escapeTemplates(tmpl, name)
61 t.nameSpace.mu.Unlock()
65 return t.text.ExecuteTemplate(wr, name, data)
68 // Parse parses a string into a template. Nested template definitions
69 // will be associated with the top-level template t. Parse may be
70 // called multiple times to parse definitions of templates to associate
71 // with t. It is an error if a resulting template is non-empty (contains
72 // content other than template definitions) and would replace a
73 // non-empty template with the same name. (In multiple calls to Parse
74 // with the same receiver template, only one call can contain text
75 // other than space, comments, and template definitions.)
76 func (t *Template) Parse(src string) (*Template, error) {
79 t.nameSpace.mu.Unlock()
80 ret, err := t.text.Parse(src)
84 // In general, all the named templates might have changed underfoot.
85 // Regardless, some new ones may have been defined.
86 // The template.Template set has been updated; update ours.
88 defer t.nameSpace.mu.Unlock()
89 for _, v := range ret.Templates() {
101 // AddParseTree is unimplemented.
102 func (t *Template) AddParseTree(name string, tree *parse.Tree) error {
103 return fmt.Errorf("html/template: AddParseTree unimplemented")
106 // Clone is unimplemented.
107 func (t *Template) Clone(name string) error {
108 return fmt.Errorf("html/template: Clone unimplemented")
111 // New allocates a new HTML template with the given name.
112 func New(name string) *Template {
117 set: make(map[string]*Template),
120 tmpl.set[name] = tmpl
124 // New allocates a new HTML template associated with the given one
125 // and with the same delimiters. The association, which is transitive,
126 // allows one template to invoke another with a {{template}} action.
127 func (t *Template) New(name string) *Template {
128 t.nameSpace.mu.Lock()
129 defer t.nameSpace.mu.Unlock()
133 // new is the implementation of New, without the lock.
134 func (t *Template) new(name string) *Template {
140 tmpl.set[name] = tmpl
144 // Name returns the name of the template.
145 func (t *Template) Name() string {
149 // Funcs adds the elements of the argument map to the template's function map.
150 // It panics if a value in the map is not a function with appropriate return
151 // type. However, it is legal to overwrite elements of the map. The return
152 // value is the template, so calls can be chained.
153 func (t *Template) Funcs(funcMap template.FuncMap) *Template {
154 t.text.Funcs(funcMap)
158 // Delims sets the action delimiters to the specified strings, to be used in
159 // subsequent calls to Parse, ParseFiles, or ParseGlob. Nested template
160 // definitions will inherit the settings. An empty delimiter stands for the
161 // corresponding default: {{ or }}.
162 // The return value is the template, so calls can be chained.
163 func (t *Template) Delims(left, right string) *Template {
164 t.text.Delims(left, right)
168 // Lookup returns the template with the given name that is associated with t,
169 // or nil if there is no such template.
170 func (t *Template) Lookup(name string) *Template {
171 t.nameSpace.mu.Lock()
172 defer t.nameSpace.mu.Unlock()
176 // Must panics if err is non-nil in the same way as template.Must.
177 func Must(t *Template, err error) *Template {
178 t.text = template.Must(t.text, err)
182 // ParseFiles creates a new Template and parses the template definitions from
183 // the named files. The returned template's name will have the (base) name and
184 // (parsed) contents of the first file. There must be at least one file.
185 // If an error occurs, parsing stops and the returned *Template is nil.
186 func ParseFiles(filenames ...string) (*Template, error) {
187 return parseFiles(nil, filenames...)
190 // ParseFiles parses the named files and associates the resulting templates with
191 // t. If an error occurs, parsing stops and the returned template is nil;
192 // otherwise it is t. There must be at least one file.
193 func (t *Template) ParseFiles(filenames ...string) (*Template, error) {
194 return parseFiles(t, filenames...)
197 // parseFiles is the helper for the method and function. If the argument
198 // template is nil, it is created from the first file.
199 func parseFiles(t *Template, filenames ...string) (*Template, error) {
200 if len(filenames) == 0 {
201 // Not really a problem, but be consistent.
202 return nil, fmt.Errorf("template: no files named in call to ParseFiles")
204 for _, filename := range filenames {
205 b, err := ioutil.ReadFile(filename)
210 name := filepath.Base(filename)
211 // First template becomes return value if not already defined,
212 // and we use that one for subsequent New calls to associate
213 // all the templates together. Also, if this file has the same name
214 // as t, this file becomes the contents of t, so
215 // t, err := New(name).Funcs(xxx).ParseFiles(name)
216 // works. Otherwise we create a new template associated with t.
221 if name == t.Name() {
226 _, err = tmpl.Parse(s)
234 // ParseGlob creates a new Template and parses the template definitions from the
235 // files identified by the pattern, which must match at least one file. The
236 // returned template will have the (base) name and (parsed) contents of the
237 // first file matched by the pattern. ParseGlob is equivalent to calling
238 // ParseFiles with the list of files matched by the pattern.
239 func ParseGlob(pattern string) (*Template, error) {
240 return parseGlob(nil, pattern)
243 // ParseGlob parses the template definitions in the files identified by the
244 // pattern and associates the resulting templates with t. The pattern is
245 // processed by filepath.Glob and must match at least one file. ParseGlob is
246 // equivalent to calling t.ParseFiles with the list of files matched by the
248 func (t *Template) ParseGlob(pattern string) (*Template, error) {
249 return parseGlob(t, pattern)
252 // parseGlob is the implementation of the function and method ParseGlob.
253 func parseGlob(t *Template, pattern string) (*Template, error) {
254 filenames, err := filepath.Glob(pattern)
258 if len(filenames) == 0 {
259 return nil, fmt.Errorf("template: pattern matches no files: %#q", pattern)
261 return parseFiles(t, filenames...)