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