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  	t.muTmpl.RLock()
    94  	defer t.muTmpl.RUnlock()
    95  	for k, v := range t.tmpl {
    96  		if k == t.name {
    97  			nt.tmpl[t.name] = nt
    98  			continue
    99  		}
   100  		// The associated templates share nt's common structure.
   101  		tmpl := v.copy(nt.common)
   102  		nt.tmpl[k] = tmpl
   103  	}
   104  	t.muFuncs.RLock()
   105  	defer t.muFuncs.RUnlock()
   106  	maps.Copy(nt.parseFuncs, t.parseFuncs)
   107  	maps.Copy(nt.execFuncs, t.execFuncs)
   108  	return nt, nil
   109  }
   110  
   111  // copy returns a shallow copy of t, with common set to the argument.
   112  func (t *Template) copy(c *common) *Template {
   113  	return &Template{
   114  		name:       t.name,
   115  		Tree:       t.Tree,
   116  		common:     c,
   117  		leftDelim:  t.leftDelim,
   118  		rightDelim: t.rightDelim,
   119  	}
   120  }
   121  
   122  // AddParseTree associates the argument parse tree with the template t, giving
   123  // it the specified name. If the template has not been defined, this tree becomes
   124  // its definition. If it has been defined and already has that name, the existing
   125  // definition is replaced; otherwise a new template is created, defined, and returned.
   126  func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error) {
   127  	t.init()
   128  	t.muTmpl.Lock()
   129  	defer t.muTmpl.Unlock()
   130  	nt := t
   131  	if name != t.name {
   132  		nt = t.New(name)
   133  	}
   134  	// Even if nt == t, we need to install it in the common.tmpl map.
   135  	if t.associate(nt, tree) || nt.Tree == nil {
   136  		nt.Tree = tree
   137  	}
   138  	return nt, nil
   139  }
   140  
   141  // Templates returns a slice of defined templates associated with t.
   142  func (t *Template) Templates() []*Template {
   143  	if t.common == nil {
   144  		return nil
   145  	}
   146  	// Return a slice so we don't expose the map.
   147  	t.muTmpl.RLock()
   148  	defer t.muTmpl.RUnlock()
   149  	m := make([]*Template, 0, len(t.tmpl))
   150  	for _, v := range t.tmpl {
   151  		m = append(m, v)
   152  	}
   153  	return m
   154  }
   155  
   156  // Delims sets the action delimiters to the specified strings, to be used in
   157  // subsequent calls to [Template.Parse], [Template.ParseFiles], or [Template.ParseGlob]. Nested template
   158  // definitions will inherit the settings. An empty delimiter stands for the
   159  // corresponding default: {{ or }}.
   160  // The return value is the template, so calls can be chained.
   161  func (t *Template) Delims(left, right string) *Template {
   162  	t.init()
   163  	t.leftDelim = left
   164  	t.rightDelim = right
   165  	return t
   166  }
   167  
   168  // Funcs adds the elements of the argument map to the template's function map.
   169  // It must be called before the template is parsed.
   170  // It panics if a value in the map is not a function with appropriate return
   171  // type or if the name cannot be used syntactically as a function in a template.
   172  // It is legal to overwrite elements of the map. The return value is the template,
   173  // so calls can be chained.
   174  func (t *Template) Funcs(funcMap FuncMap) *Template {
   175  	t.init()
   176  	t.muFuncs.Lock()
   177  	defer t.muFuncs.Unlock()
   178  	addValueFuncs(t.execFuncs, funcMap)
   179  	addFuncs(t.parseFuncs, funcMap)
   180  	return t
   181  }
   182  
   183  // Lookup returns the template with the given name that is associated with t.
   184  // It returns nil if there is no such template or the template has no definition.
   185  func (t *Template) Lookup(name string) *Template {
   186  	if t.common == nil {
   187  		return nil
   188  	}
   189  	t.muTmpl.RLock()
   190  	defer t.muTmpl.RUnlock()
   191  	return t.tmpl[name]
   192  }
   193  
   194  // Parse parses text as a template body for t.
   195  // Named template definitions ({{define ...}} or {{block ...}} statements) in text
   196  // define additional templates associated with t and are removed from the
   197  // definition of t itself.
   198  //
   199  // Templates can be redefined in successive calls to Parse.
   200  // A template definition with a body containing only white space and comments
   201  // is considered empty and will not replace an existing template's body.
   202  // This allows using Parse to add new named template definitions without
   203  // overwriting the main template body.
   204  func (t *Template) Parse(text string) (*Template, error) {
   205  	t.init()
   206  	t.muFuncs.RLock()
   207  	trees, err := parse.Parse(t.name, text, t.leftDelim, t.rightDelim, t.parseFuncs, builtins())
   208  	t.muFuncs.RUnlock()
   209  	if err != nil {
   210  		return nil, err
   211  	}
   212  	// Add the newly parsed trees, including the one for t, into our common structure.
   213  	for name, tree := range trees {
   214  		if _, err := t.AddParseTree(name, tree); err != nil {
   215  			return nil, err
   216  		}
   217  	}
   218  	return t, nil
   219  }
   220  
   221  // associate installs the new template into the group of templates associated
   222  // with t. The two are already known to share the common structure.
   223  // The boolean return value reports whether to store this tree as t.Tree.
   224  func (t *Template) associate(new *Template, tree *parse.Tree) bool {
   225  	if new.common != t.common {
   226  		panic("internal error: associate not common")
   227  	}
   228  	if old := t.tmpl[new.name]; old != nil && parse.IsEmptyTree(tree.Root) && old.Tree != nil {
   229  		// If a template by that name exists,
   230  		// don't replace it with an empty template.
   231  		return false
   232  	}
   233  	t.tmpl[new.name] = new
   234  	return true
   235  }
   236  

View as plain text