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