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