Run Format

Source file src/pkg/html/template/template.go

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

View as plain text