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