Source file src/text/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  	"maps"
     9  	"reflect"
    10  	"sync"
    11  	"text/template/parse"
    12  )
    13  
    14  // common holds the information shared by related templates.
    15  type common struct {
    16  	tmpl   map[string]*Template // Map from name to defined templates.
    17  	muTmpl sync.RWMutex         // protects tmpl
    18  	option option
    19  	// We use two maps, one for parsing and one for execution.
    20  	// This separation makes the API cleaner since it doesn't
    21  	// expose reflection to the client.
    22  	muFuncs    sync.RWMutex // protects parseFuncs and execFuncs
    23  	parseFuncs FuncMap
    24  	execFuncs  map[string]reflect.Value
    25  }
    26  
    27  // Template is the representation of a parsed template. The *parse.Tree
    28  // field is exported only for use by [html/template] and should be treated
    29  // as unexported by all other clients.
    30  type Template struct {
    31  	name string
    32  	*parse.Tree
    33  	*common
    34  	leftDelim  string
    35  	rightDelim string
    36  }
    37  
    38  // New allocates a new, undefined template with the given name.
    39  func New(name string) *Template {
    40  	t := &Template{
    41  		name: name,
    42  	}
    43  	t.init()
    44  	return t
    45  }
    46  
    47  // Name returns the name of the template.
    48  func (t *Template) Name() string {
    49  	return t.name
    50  }
    51  
    52  // New allocates a new, undefined template associated with the given one and with the same
    53  // delimiters. The association, which is transitive, allows one template to
    54  // invoke another with a {{template}} action.
    55  //
    56  // Because associated templates share underlying data, template construction
    57  // cannot be done safely in parallel. Once the templates are constructed, they
    58  // can be executed in parallel.
    59  func (t *Template) New(name string) *Template {
    60  	t.init()
    61  	nt := &Template{
    62  		name:       name,
    63  		common:     t.common,
    64  		leftDelim:  t.leftDelim,
    65  		rightDelim: t.rightDelim,
    66  	}
    67  	return nt
    68  }
    69  
    70  // init guarantees that t has a valid common structure.
    71  func (t *Template) init() {
    72  	if t.common == nil {
    73  		c := new(common)
    74  		c.tmpl = make(map[string]*Template)
    75  		c.parseFuncs = make(FuncMap)
    76  		c.execFuncs = make(map[string]reflect.Value)
    77  		t.common = c
    78  	}
    79  }
    80  
    81  // Clone returns a duplicate of the template, including all associated
    82  // templates. The actual representation is not copied, but the name space of
    83  // associated templates is, so further calls to [Template.Parse] in the copy will add
    84  // templates to the copy but not to the original. Clone can be used to prepare
    85  // common templates and use them with variant definitions for other templates
    86  // by adding the variants after the clone is made.
    87  func (t *Template) Clone() (*Template, error) {
    88  	nt := t.copy(nil)
    89  	nt.init()
    90  	if t.common == nil {
    91  		return nt, nil
    92  	}
    93  	nt.option = t.option
    94  	t.muTmpl.RLock()
    95  	defer t.muTmpl.RUnlock()
    96  	for k, v := range t.tmpl {
    97  		if k == t.name {
    98  			nt.tmpl[t.name] = nt
    99  			continue
   100  		}
   101  		// The associated templates share nt's common structure.
   102  		tmpl := v.copy(nt.common)
   103  		nt.tmpl[k] = tmpl
   104  	}
   105  	t.muFuncs.RLock()
   106  	defer t.muFuncs.RUnlock()
   107  	maps.Copy(nt.parseFuncs, t.parseFuncs)
   108  	maps.Copy(nt.execFuncs, t.execFuncs)
   109  	return nt, nil
   110  }
   111  
   112  // copy returns a shallow copy of t, with common set to the argument.
   113  func (t *Template) copy(c *common) *Template {
   114  	return &Template{
   115  		name:       t.name,
   116  		Tree:       t.Tree,
   117  		common:     c,
   118  		leftDelim:  t.leftDelim,
   119  		rightDelim: t.rightDelim,
   120  	}
   121  }
   122  
   123  // AddParseTree associates the argument parse tree with the template t, giving
   124  // it the specified name. If the template has not been defined, this tree becomes
   125  // its definition. If it has been defined and already has that name, the existing
   126  // definition is replaced; otherwise a new template is created, defined, and returned.
   127  func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error) {
   128  	t.init()
   129  	t.muTmpl.Lock()
   130  	defer t.muTmpl.Unlock()
   131  	nt := t
   132  	if name != t.name {
   133  		nt = t.New(name)
   134  	}
   135  	// Even if nt == t, we need to install it in the common.tmpl map.
   136  	if t.associate(nt, tree) || nt.Tree == nil {
   137  		nt.Tree = tree
   138  	}
   139  	return nt, nil
   140  }
   141  
   142  // Templates returns a slice of defined templates associated with t.
   143  func (t *Template) Templates() []*Template {
   144  	if t.common == nil {
   145  		return nil
   146  	}
   147  	// Return a slice so we don't expose the map.
   148  	t.muTmpl.RLock()
   149  	defer t.muTmpl.RUnlock()
   150  	m := make([]*Template, 0, len(t.tmpl))
   151  	for _, v := range t.tmpl {
   152  		m = append(m, v)
   153  	}
   154  	return m
   155  }
   156  
   157  // Delims sets the action delimiters to the specified strings, to be used in
   158  // subsequent calls to [Template.Parse], [Template.ParseFiles], or [Template.ParseGlob]. Nested template
   159  // definitions will inherit the settings. An empty delimiter stands for the
   160  // corresponding default: {{ or }}.
   161  // The return value is the template, so calls can be chained.
   162  func (t *Template) Delims(left, right string) *Template {
   163  	t.init()
   164  	t.leftDelim = left
   165  	t.rightDelim = right
   166  	return t
   167  }
   168  
   169  // Funcs adds the elements of the argument map to the template's function map.
   170  // It must be called before the template is parsed.
   171  // It panics if a value in the map is not a function with appropriate return
   172  // type or if the name cannot be used syntactically as a function in a template.
   173  // It is legal to overwrite elements of the map. The return value is the template,
   174  // so calls can be chained.
   175  func (t *Template) Funcs(funcMap FuncMap) *Template {
   176  	t.init()
   177  	t.muFuncs.Lock()
   178  	defer t.muFuncs.Unlock()
   179  	addValueFuncs(t.execFuncs, funcMap)
   180  	addFuncs(t.parseFuncs, funcMap)
   181  	return t
   182  }
   183  
   184  // Lookup returns the template with the given name that is associated with t.
   185  // It returns nil if there is no such template or the template has no definition.
   186  func (t *Template) Lookup(name string) *Template {
   187  	if t.common == nil {
   188  		return nil
   189  	}
   190  	t.muTmpl.RLock()
   191  	defer t.muTmpl.RUnlock()
   192  	return t.tmpl[name]
   193  }
   194  
   195  // Parse parses text as a template body for t.
   196  // Named template definitions ({{define ...}} or {{block ...}} statements) in text
   197  // define additional templates associated with t and are removed from the
   198  // definition of t itself.
   199  //
   200  // Templates can be redefined in successive calls to Parse.
   201  // A template definition with a body containing only white space and comments
   202  // is considered empty and will not replace an existing template's body.
   203  // This allows using Parse to add new named template definitions without
   204  // overwriting the main template body.
   205  func (t *Template) Parse(text string) (*Template, error) {
   206  	t.init()
   207  	t.muFuncs.RLock()
   208  	trees, err := parse.Parse(t.name, text, t.leftDelim, t.rightDelim, t.parseFuncs, builtins())
   209  	t.muFuncs.RUnlock()
   210  	if err != nil {
   211  		return nil, err
   212  	}
   213  	// Add the newly parsed trees, including the one for t, into our common structure.
   214  	for name, tree := range trees {
   215  		if _, err := t.AddParseTree(name, tree); err != nil {
   216  			return nil, err
   217  		}
   218  	}
   219  	return t, nil
   220  }
   221  
   222  // associate installs the new template into the group of templates associated
   223  // with t. The two are already known to share the common structure.
   224  // The boolean return value reports whether to store this tree as t.Tree.
   225  func (t *Template) associate(new *Template, tree *parse.Tree) bool {
   226  	if new.common != t.common {
   227  		panic("internal error: associate not common")
   228  	}
   229  	if old := t.tmpl[new.name]; old != nil && parse.IsEmptyTree(tree.Root) && old.Tree != nil {
   230  		// If a template by that name exists,
   231  		// don't replace it with an empty template.
   232  		return false
   233  	}
   234  	t.tmpl[new.name] = new
   235  	return true
   236  }
   237  

View as plain text