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