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