github.com/ActiveState/go@v0.0.0-20170614201249-0b81c023a722/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, although if parallel
   116  // executions share a Writer the output may be interleaved.
   117  func (t *Template) Execute(wr io.Writer, data interface{}) error {
   118  	if err := t.escape(); err != nil {
   119  		return err
   120  	}
   121  	return t.text.Execute(wr, data)
   122  }
   123  
   124  // ExecuteTemplate applies the template associated with t that has the given
   125  // name to the specified data object and writes the output to wr.
   126  // If an error occurs executing the template or writing its output,
   127  // execution stops, but partial results may already have been written to
   128  // the output writer.
   129  // A template may be executed safely in parallel, although if parallel
   130  // executions share a Writer the output may be interleaved.
   131  func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
   132  	tmpl, err := t.lookupAndEscapeTemplate(name)
   133  	if err != nil {
   134  		return err
   135  	}
   136  	return tmpl.text.Execute(wr, data)
   137  }
   138  
   139  // lookupAndEscapeTemplate guarantees that the template with the given name
   140  // is escaped, or returns an error if it cannot be. It returns the named
   141  // template.
   142  func (t *Template) lookupAndEscapeTemplate(name string) (tmpl *Template, err error) {
   143  	t.nameSpace.mu.Lock()
   144  	defer t.nameSpace.mu.Unlock()
   145  	t.nameSpace.escaped = true
   146  	tmpl = t.set[name]
   147  	if tmpl == nil {
   148  		return nil, fmt.Errorf("html/template: %q is undefined", name)
   149  	}
   150  	if tmpl.escapeErr != nil && tmpl.escapeErr != escapeOK {
   151  		return nil, tmpl.escapeErr
   152  	}
   153  	if tmpl.text.Tree == nil || tmpl.text.Root == nil {
   154  		return nil, fmt.Errorf("html/template: %q is an incomplete template", name)
   155  	}
   156  	if t.text.Lookup(name) == nil {
   157  		panic("html/template internal error: template escaping out of sync")
   158  	}
   159  	if tmpl.escapeErr == nil {
   160  		err = escapeTemplate(tmpl, tmpl.text.Root, name)
   161  	}
   162  	return tmpl, err
   163  }
   164  
   165  // DefinedTemplates returns a string listing the defined templates,
   166  // prefixed by the string "; defined templates are: ". If there are none,
   167  // it returns the empty string. Used to generate an error message.
   168  func (t *Template) DefinedTemplates() string {
   169  	return t.text.DefinedTemplates()
   170  }
   171  
   172  // Parse parses text as a template body for t.
   173  // Named template definitions ({{define ...}} or {{block ...}} statements) in text
   174  // define additional templates associated with t and are removed from the
   175  // definition of t itself.
   176  //
   177  // Templates can be redefined in successive calls to Parse,
   178  // before the first use of Execute on t or any associated template.
   179  // A template definition with a body containing only white space and comments
   180  // is considered empty and will not replace an existing template's body.
   181  // This allows using Parse to add new named template definitions without
   182  // overwriting the main template body.
   183  func (t *Template) Parse(text string) (*Template, error) {
   184  	if err := t.checkCanParse(); err != nil {
   185  		return nil, err
   186  	}
   187  
   188  	ret, err := t.text.Parse(text)
   189  	if err != nil {
   190  		return nil, err
   191  	}
   192  
   193  	// In general, all the named templates might have changed underfoot.
   194  	// Regardless, some new ones may have been defined.
   195  	// The template.Template set has been updated; update ours.
   196  	t.nameSpace.mu.Lock()
   197  	defer t.nameSpace.mu.Unlock()
   198  	for _, v := range ret.Templates() {
   199  		name := v.Name()
   200  		tmpl := t.set[name]
   201  		if tmpl == nil {
   202  			tmpl = t.new(name)
   203  		}
   204  		tmpl.text = v
   205  		tmpl.Tree = v.Tree
   206  	}
   207  	return t, nil
   208  }
   209  
   210  // AddParseTree creates a new template with the name and parse tree
   211  // and associates it with t.
   212  //
   213  // It returns an error if t or any associated template has already been executed.
   214  func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error) {
   215  	if err := t.checkCanParse(); err != nil {
   216  		return nil, err
   217  	}
   218  
   219  	t.nameSpace.mu.Lock()
   220  	defer t.nameSpace.mu.Unlock()
   221  	text, err := t.text.AddParseTree(name, tree)
   222  	if err != nil {
   223  		return nil, err
   224  	}
   225  	ret := &Template{
   226  		nil,
   227  		text,
   228  		text.Tree,
   229  		t.nameSpace,
   230  	}
   231  	t.set[name] = ret
   232  	return ret, nil
   233  }
   234  
   235  // Clone returns a duplicate of the template, including all associated
   236  // templates. The actual representation is not copied, but the name space of
   237  // associated templates is, so further calls to Parse in the copy will add
   238  // templates to the copy but not to the original. Clone can be used to prepare
   239  // common templates and use them with variant definitions for other templates
   240  // by adding the variants after the clone is made.
   241  //
   242  // It returns an error if t has already been executed.
   243  func (t *Template) Clone() (*Template, error) {
   244  	t.nameSpace.mu.Lock()
   245  	defer t.nameSpace.mu.Unlock()
   246  	if t.escapeErr != nil {
   247  		return nil, fmt.Errorf("html/template: cannot Clone %q after it has executed", t.Name())
   248  	}
   249  	textClone, err := t.text.Clone()
   250  	if err != nil {
   251  		return nil, err
   252  	}
   253  	ret := &Template{
   254  		nil,
   255  		textClone,
   256  		textClone.Tree,
   257  		&nameSpace{
   258  			set: make(map[string]*Template),
   259  		},
   260  	}
   261  	ret.set[ret.Name()] = ret
   262  	for _, x := range textClone.Templates() {
   263  		name := x.Name()
   264  		src := t.set[name]
   265  		if src == nil || src.escapeErr != nil {
   266  			return nil, fmt.Errorf("html/template: cannot Clone %q after it has executed", t.Name())
   267  		}
   268  		x.Tree = x.Tree.Copy()
   269  		ret.set[name] = &Template{
   270  			nil,
   271  			x,
   272  			x.Tree,
   273  			ret.nameSpace,
   274  		}
   275  	}
   276  	// Return the template associated with the name of this template.
   277  	return ret.set[ret.Name()], 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 must be called before the template is parsed.
   331  // It panics if a value in the map is not a function with appropriate return
   332  // type. However, it is legal to overwrite elements of the map. The return
   333  // value is the template, so calls can be chained.
   334  func (t *Template) Funcs(funcMap FuncMap) *Template {
   335  	t.text.Funcs(template.FuncMap(funcMap))
   336  	return t
   337  }
   338  
   339  // Delims sets the action delimiters to the specified strings, to be used in
   340  // subsequent calls to Parse, ParseFiles, or ParseGlob. Nested template
   341  // definitions will inherit the settings. An empty delimiter stands for the
   342  // corresponding default: {{ or }}.
   343  // The return value is the template, so calls can be chained.
   344  func (t *Template) Delims(left, right string) *Template {
   345  	t.text.Delims(left, right)
   346  	return t
   347  }
   348  
   349  // Lookup returns the template with the given name that is associated with t,
   350  // or nil if there is no such template.
   351  func (t *Template) Lookup(name string) *Template {
   352  	t.nameSpace.mu.Lock()
   353  	defer t.nameSpace.mu.Unlock()
   354  	return t.set[name]
   355  }
   356  
   357  // Must is a helper that wraps a call to a function returning (*Template, error)
   358  // and panics if the error is non-nil. It is intended for use in variable initializations
   359  // such as
   360  //	var t = template.Must(template.New("name").Parse("html"))
   361  func Must(t *Template, err error) *Template {
   362  	if err != nil {
   363  		panic(err)
   364  	}
   365  	return t
   366  }
   367  
   368  // ParseFiles creates a new Template and parses the template definitions from
   369  // the named files. The returned template's name will have the (base) name and
   370  // (parsed) contents of the first file. There must be at least one file.
   371  // If an error occurs, parsing stops and the returned *Template is nil.
   372  //
   373  // When parsing multiple files with the same name in different directories,
   374  // the last one mentioned will be the one that results.
   375  // For instance, ParseFiles("a/foo", "b/foo") stores "b/foo" as the template
   376  // named "foo", while "a/foo" is unavailable.
   377  func ParseFiles(filenames ...string) (*Template, error) {
   378  	return parseFiles(nil, filenames...)
   379  }
   380  
   381  // ParseFiles parses the named files and associates the resulting templates with
   382  // t. If an error occurs, parsing stops and the returned template is nil;
   383  // otherwise it is t. There must be at least one file.
   384  //
   385  // When parsing multiple files with the same name in different directories,
   386  // the last one mentioned will be the one that results.
   387  //
   388  // ParseFiles returns an error if t or any associated template has already been executed.
   389  func (t *Template) ParseFiles(filenames ...string) (*Template, error) {
   390  	return parseFiles(t, filenames...)
   391  }
   392  
   393  // parseFiles is the helper for the method and function. If the argument
   394  // template is nil, it is created from the first file.
   395  func parseFiles(t *Template, filenames ...string) (*Template, error) {
   396  	if err := t.checkCanParse(); err != nil {
   397  		return nil, err
   398  	}
   399  
   400  	if len(filenames) == 0 {
   401  		// Not really a problem, but be consistent.
   402  		return nil, fmt.Errorf("html/template: no files named in call to ParseFiles")
   403  	}
   404  	for _, filename := range filenames {
   405  		b, err := ioutil.ReadFile(filename)
   406  		if err != nil {
   407  			return nil, err
   408  		}
   409  		s := string(b)
   410  		name := filepath.Base(filename)
   411  		// First template becomes return value if not already defined,
   412  		// and we use that one for subsequent New calls to associate
   413  		// all the templates together. Also, if this file has the same name
   414  		// as t, this file becomes the contents of t, so
   415  		//  t, err := New(name).Funcs(xxx).ParseFiles(name)
   416  		// works. Otherwise we create a new template associated with t.
   417  		var tmpl *Template
   418  		if t == nil {
   419  			t = New(name)
   420  		}
   421  		if name == t.Name() {
   422  			tmpl = t
   423  		} else {
   424  			tmpl = t.New(name)
   425  		}
   426  		_, err = tmpl.Parse(s)
   427  		if err != nil {
   428  			return nil, err
   429  		}
   430  	}
   431  	return t, nil
   432  }
   433  
   434  // ParseGlob creates a new Template and parses the template definitions from the
   435  // files identified by the pattern, which must match at least one file. The
   436  // returned template will have the (base) name and (parsed) contents of the
   437  // first file matched by the pattern. ParseGlob is equivalent to calling
   438  // ParseFiles with the list of files matched by the pattern.
   439  //
   440  // When parsing multiple files with the same name in different directories,
   441  // the last one mentioned will be the one that results.
   442  func ParseGlob(pattern string) (*Template, error) {
   443  	return parseGlob(nil, pattern)
   444  }
   445  
   446  // ParseGlob parses the template definitions in the files identified by the
   447  // pattern and associates the resulting templates with t. The pattern is
   448  // processed by filepath.Glob and must match at least one file. ParseGlob is
   449  // equivalent to calling t.ParseFiles with the list of files matched by the
   450  // pattern.
   451  //
   452  // When parsing multiple files with the same name in different directories,
   453  // the last one mentioned will be the one that results.
   454  //
   455  // ParseGlob returns an error if t or any associated template has already been executed.
   456  func (t *Template) ParseGlob(pattern string) (*Template, error) {
   457  	return parseGlob(t, pattern)
   458  }
   459  
   460  // parseGlob is the implementation of the function and method ParseGlob.
   461  func parseGlob(t *Template, pattern string) (*Template, error) {
   462  	if err := t.checkCanParse(); err != nil {
   463  		return nil, err
   464  	}
   465  	filenames, err := filepath.Glob(pattern)
   466  	if err != nil {
   467  		return nil, err
   468  	}
   469  	if len(filenames) == 0 {
   470  		return nil, fmt.Errorf("html/template: pattern matches no files: %#q", pattern)
   471  	}
   472  	return parseFiles(t, filenames...)
   473  }
   474  
   475  // IsTrue reports whether the value is 'true', in the sense of not the zero of its type,
   476  // and whether the value has a meaningful truth value. This is the definition of
   477  // truth used by if and other such actions.
   478  func IsTrue(val interface{}) (truth, ok bool) {
   479  	return template.IsTrue(val)
   480  }