github.com/ader1990/go@v0.0.0-20140630135419-8c24447fa791/src/pkg/html/template/template.go (about) 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/ioutil" 11 "path/filepath" 12 "sync" 13 "text/template" 14 "text/template/parse" 15 ) 16 17 // Template is a specialized Template from "text/template" that produces a safe 18 // HTML document fragment. 19 type Template struct { 20 escaped bool 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 // The underlying template's parse tree, updated to be HTML-safe. 26 Tree *parse.Tree 27 *nameSpace // common to all associated templates 28 } 29 30 // nameSpace is the data structure shared by all templates in an association. 31 type nameSpace struct { 32 mu sync.Mutex 33 set map[string]*Template 34 } 35 36 // Templates returns a slice of the templates associated with t, including t 37 // itself. 38 func (t *Template) Templates() []*Template { 39 ns := t.nameSpace 40 ns.mu.Lock() 41 defer ns.mu.Unlock() 42 // Return a slice so we don't expose the map. 43 m := make([]*Template, 0, len(ns.set)) 44 for _, v := range ns.set { 45 m = append(m, v) 46 } 47 return m 48 } 49 50 // escape escapes all associated templates. 51 func (t *Template) escape() error { 52 t.nameSpace.mu.Lock() 53 defer t.nameSpace.mu.Unlock() 54 if !t.escaped { 55 if err := escapeTemplates(t, t.Name()); err != nil { 56 return err 57 } 58 t.escaped = true 59 } 60 return nil 61 } 62 63 // Execute applies a parsed template to the specified data object, 64 // writing the output to wr. 65 // If an error occurs executing the template or writing its output, 66 // execution stops, but partial results may already have been written to 67 // the output writer. 68 // A template may be executed safely in parallel. 69 func (t *Template) Execute(wr io.Writer, data interface{}) error { 70 if err := t.escape(); err != nil { 71 return err 72 } 73 return t.text.Execute(wr, data) 74 } 75 76 // ExecuteTemplate applies the template associated with t that has the given 77 // name to the specified data object and writes the output to wr. 78 // If an error occurs executing the template or writing its output, 79 // execution stops, but partial results may already have been written to 80 // the output writer. 81 // A template may be executed safely in parallel. 82 func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error { 83 tmpl, err := t.lookupAndEscapeTemplate(name) 84 if err != nil { 85 return err 86 } 87 return tmpl.text.Execute(wr, data) 88 } 89 90 // lookupAndEscapeTemplate guarantees that the template with the given name 91 // is escaped, or returns an error if it cannot be. It returns the named 92 // template. 93 func (t *Template) lookupAndEscapeTemplate(name string) (tmpl *Template, err error) { 94 t.nameSpace.mu.Lock() 95 defer t.nameSpace.mu.Unlock() 96 tmpl = t.set[name] 97 if tmpl == nil { 98 return nil, fmt.Errorf("html/template: %q is undefined", name) 99 } 100 if tmpl.text.Tree == nil || tmpl.text.Root == nil { 101 return nil, fmt.Errorf("html/template: %q is an incomplete template", name) 102 } 103 if t.text.Lookup(name) == nil { 104 panic("html/template internal error: template escaping out of sync") 105 } 106 if tmpl != nil && !tmpl.escaped { 107 err = escapeTemplates(tmpl, name) 108 } 109 return tmpl, err 110 } 111 112 // Parse parses a string into a template. Nested template definitions 113 // will be associated with the top-level template t. Parse may be 114 // called multiple times to parse definitions of templates to associate 115 // with t. It is an error if a resulting template is non-empty (contains 116 // content other than template definitions) and would replace a 117 // non-empty template with the same name. (In multiple calls to Parse 118 // with the same receiver template, only one call can contain text 119 // other than space, comments, and template definitions.) 120 func (t *Template) Parse(src string) (*Template, error) { 121 t.nameSpace.mu.Lock() 122 t.escaped = false 123 t.nameSpace.mu.Unlock() 124 ret, err := t.text.Parse(src) 125 if err != nil { 126 return nil, err 127 } 128 // In general, all the named templates might have changed underfoot. 129 // Regardless, some new ones may have been defined. 130 // The template.Template set has been updated; update ours. 131 t.nameSpace.mu.Lock() 132 defer t.nameSpace.mu.Unlock() 133 for _, v := range ret.Templates() { 134 name := v.Name() 135 tmpl := t.set[name] 136 if tmpl == nil { 137 tmpl = t.new(name) 138 } 139 // Restore our record of this text/template to its unescaped original state. 140 tmpl.escaped = false 141 tmpl.text = v 142 tmpl.Tree = v.Tree 143 } 144 return t, nil 145 } 146 147 // AddParseTree creates a new template with the name and parse tree 148 // and associates it with t. 149 // 150 // It returns an error if t has already been executed. 151 func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error) { 152 t.nameSpace.mu.Lock() 153 defer t.nameSpace.mu.Unlock() 154 if t.escaped { 155 return nil, fmt.Errorf("html/template: cannot AddParseTree to %q after it has executed", t.Name()) 156 } 157 text, err := t.text.AddParseTree(name, tree) 158 if err != nil { 159 return nil, err 160 } 161 ret := &Template{ 162 false, 163 text, 164 text.Tree, 165 t.nameSpace, 166 } 167 t.set[name] = ret 168 return ret, nil 169 } 170 171 // Clone returns a duplicate of the template, including all associated 172 // templates. The actual representation is not copied, but the name space of 173 // associated templates is, so further calls to Parse in the copy will add 174 // templates to the copy but not to the original. Clone can be used to prepare 175 // common templates and use them with variant definitions for other templates 176 // by adding the variants after the clone is made. 177 // 178 // It returns an error if t has already been executed. 179 func (t *Template) Clone() (*Template, error) { 180 t.nameSpace.mu.Lock() 181 defer t.nameSpace.mu.Unlock() 182 if t.escaped { 183 return nil, fmt.Errorf("html/template: cannot Clone %q after it has executed", t.Name()) 184 } 185 textClone, err := t.text.Clone() 186 if err != nil { 187 return nil, err 188 } 189 ret := &Template{ 190 false, 191 textClone, 192 textClone.Tree, 193 &nameSpace{ 194 set: make(map[string]*Template), 195 }, 196 } 197 for _, x := range textClone.Templates() { 198 name := x.Name() 199 src := t.set[name] 200 if src == nil || src.escaped { 201 return nil, fmt.Errorf("html/template: cannot Clone %q after it has executed", t.Name()) 202 } 203 x.Tree = x.Tree.Copy() 204 ret.set[name] = &Template{ 205 false, 206 x, 207 x.Tree, 208 ret.nameSpace, 209 } 210 } 211 return ret, nil 212 } 213 214 // New allocates a new HTML template with the given name. 215 func New(name string) *Template { 216 tmpl := &Template{ 217 false, 218 template.New(name), 219 nil, 220 &nameSpace{ 221 set: make(map[string]*Template), 222 }, 223 } 224 tmpl.set[name] = tmpl 225 return tmpl 226 } 227 228 // New allocates a new HTML template associated with the given one 229 // and with the same delimiters. The association, which is transitive, 230 // allows one template to invoke another with a {{template}} action. 231 func (t *Template) New(name string) *Template { 232 t.nameSpace.mu.Lock() 233 defer t.nameSpace.mu.Unlock() 234 return t.new(name) 235 } 236 237 // new is the implementation of New, without the lock. 238 func (t *Template) new(name string) *Template { 239 tmpl := &Template{ 240 false, 241 t.text.New(name), 242 nil, 243 t.nameSpace, 244 } 245 tmpl.set[name] = tmpl 246 return tmpl 247 } 248 249 // Name returns the name of the template. 250 func (t *Template) Name() string { 251 return t.text.Name() 252 } 253 254 // FuncMap is the type of the map defining the mapping from names to 255 // functions. Each function must have either a single return value, or two 256 // return values of which the second has type error. In that case, if the 257 // second (error) argument evaluates to non-nil during execution, execution 258 // terminates and Execute returns that error. FuncMap has the same base type 259 // as FuncMap in "text/template", copied here so clients need not import 260 // "text/template". 261 type FuncMap map[string]interface{} 262 263 // Funcs adds the elements of the argument map to the template's function map. 264 // It panics if a value in the map is not a function with appropriate return 265 // type. However, it is legal to overwrite elements of the map. The return 266 // value is the template, so calls can be chained. 267 func (t *Template) Funcs(funcMap FuncMap) *Template { 268 t.text.Funcs(template.FuncMap(funcMap)) 269 return t 270 } 271 272 // Delims sets the action delimiters to the specified strings, to be used in 273 // subsequent calls to Parse, ParseFiles, or ParseGlob. Nested template 274 // definitions will inherit the settings. An empty delimiter stands for the 275 // corresponding default: {{ or }}. 276 // The return value is the template, so calls can be chained. 277 func (t *Template) Delims(left, right string) *Template { 278 t.text.Delims(left, right) 279 return t 280 } 281 282 // Lookup returns the template with the given name that is associated with t, 283 // or nil if there is no such template. 284 func (t *Template) Lookup(name string) *Template { 285 t.nameSpace.mu.Lock() 286 defer t.nameSpace.mu.Unlock() 287 return t.set[name] 288 } 289 290 // Must is a helper that wraps a call to a function returning (*Template, error) 291 // and panics if the error is non-nil. It is intended for use in variable initializations 292 // such as 293 // var t = template.Must(template.New("name").Parse("html")) 294 func Must(t *Template, err error) *Template { 295 if err != nil { 296 panic(err) 297 } 298 return t 299 } 300 301 // ParseFiles creates a new Template and parses the template definitions from 302 // the named files. The returned template's name will have the (base) name and 303 // (parsed) contents of the first file. There must be at least one file. 304 // If an error occurs, parsing stops and the returned *Template is nil. 305 func ParseFiles(filenames ...string) (*Template, error) { 306 return parseFiles(nil, filenames...) 307 } 308 309 // ParseFiles parses the named files and associates the resulting templates with 310 // t. If an error occurs, parsing stops and the returned template is nil; 311 // otherwise it is t. There must be at least one file. 312 func (t *Template) ParseFiles(filenames ...string) (*Template, error) { 313 return parseFiles(t, filenames...) 314 } 315 316 // parseFiles is the helper for the method and function. If the argument 317 // template is nil, it is created from the first file. 318 func parseFiles(t *Template, filenames ...string) (*Template, error) { 319 if len(filenames) == 0 { 320 // Not really a problem, but be consistent. 321 return nil, fmt.Errorf("html/template: no files named in call to ParseFiles") 322 } 323 for _, filename := range filenames { 324 b, err := ioutil.ReadFile(filename) 325 if err != nil { 326 return nil, err 327 } 328 s := string(b) 329 name := filepath.Base(filename) 330 // First template becomes return value if not already defined, 331 // and we use that one for subsequent New calls to associate 332 // all the templates together. Also, if this file has the same name 333 // as t, this file becomes the contents of t, so 334 // t, err := New(name).Funcs(xxx).ParseFiles(name) 335 // works. Otherwise we create a new template associated with t. 336 var tmpl *Template 337 if t == nil { 338 t = New(name) 339 } 340 if name == t.Name() { 341 tmpl = t 342 } else { 343 tmpl = t.New(name) 344 } 345 _, err = tmpl.Parse(s) 346 if err != nil { 347 return nil, err 348 } 349 } 350 return t, nil 351 } 352 353 // ParseGlob creates a new Template and parses the template definitions from the 354 // files identified by the pattern, which must match at least one file. The 355 // returned template will have the (base) name and (parsed) contents of the 356 // first file matched by the pattern. ParseGlob is equivalent to calling 357 // ParseFiles with the list of files matched by the pattern. 358 func ParseGlob(pattern string) (*Template, error) { 359 return parseGlob(nil, pattern) 360 } 361 362 // ParseGlob parses the template definitions in the files identified by the 363 // pattern and associates the resulting templates with t. The pattern is 364 // processed by filepath.Glob and must match at least one file. ParseGlob is 365 // equivalent to calling t.ParseFiles with the list of files matched by the 366 // pattern. 367 func (t *Template) ParseGlob(pattern string) (*Template, error) { 368 return parseGlob(t, pattern) 369 } 370 371 // parseGlob is the implementation of the function and method ParseGlob. 372 func parseGlob(t *Template, pattern string) (*Template, error) { 373 filenames, err := filepath.Glob(pattern) 374 if err != nil { 375 return nil, err 376 } 377 if len(filenames) == 0 { 378 return nil, fmt.Errorf("html/template: pattern matches no files: %#q", pattern) 379 } 380 return parseFiles(t, filenames...) 381 }