...

Source file src/text/template/template.go

Documentation: text/template

     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  // Any function used in the template must be added before the template is
   171  // parsed. Funcs may be called more than once, including after parsing (for
   172  // example, after [Template.Clone]), to replace a function of the same name;
   173  // the replacement is used when the template is executed.
   174  // It panics if a value in the map is not a function with appropriate return
   175  // type or if the name cannot be used syntactically as a function in a template.
   176  // The return value is the template, so calls can be chained.
   177  func (t *Template) Funcs(funcMap FuncMap) *Template {
   178  	t.init()
   179  	t.muFuncs.Lock()
   180  	defer t.muFuncs.Unlock()
   181  	addValueFuncs(t.execFuncs, funcMap)
   182  	addFuncs(t.parseFuncs, funcMap)
   183  	return t
   184  }
   185  
   186  // Lookup returns the template with the given name that is associated with t.
   187  // It returns nil if there is no such template or the template has no definition.
   188  func (t *Template) Lookup(name string) *Template {
   189  	if t.common == nil {
   190  		return nil
   191  	}
   192  	t.muTmpl.RLock()
   193  	defer t.muTmpl.RUnlock()
   194  	return t.tmpl[name]
   195  }
   196  
   197  // Parse parses text as a template body for t.
   198  // Named template definitions ({{define ...}} or {{block ...}} statements) in text
   199  // define additional templates associated with t and are removed from the
   200  // definition of t itself.
   201  //
   202  // Templates can be redefined in successive calls to Parse.
   203  // A template definition with a body containing only white space and comments
   204  // is considered empty and will not replace an existing template's body.
   205  // This allows using Parse to add new named template definitions without
   206  // overwriting the main template body.
   207  func (t *Template) Parse(text string) (*Template, error) {
   208  	t.init()
   209  	t.muFuncs.RLock()
   210  	trees, err := parse.Parse(t.name, text, t.leftDelim, t.rightDelim, t.parseFuncs, builtins())
   211  	t.muFuncs.RUnlock()
   212  	if err != nil {
   213  		return nil, err
   214  	}
   215  	// Add the newly parsed trees, including the one for t, into our common structure.
   216  	for name, tree := range trees {
   217  		if _, err := t.AddParseTree(name, tree); err != nil {
   218  			return nil, err
   219  		}
   220  	}
   221  	return t, nil
   222  }
   223  
   224  // associate installs the new template into the group of templates associated
   225  // with t. The two are already known to share the common structure.
   226  // The boolean return value reports whether to store this tree as t.Tree.
   227  func (t *Template) associate(new *Template, tree *parse.Tree) bool {
   228  	if new.common != t.common {
   229  		panic("internal error: associate not common")
   230  	}
   231  	if old := t.tmpl[new.name]; old != nil && parse.IsEmptyTree(tree.Root) && old.Tree != nil {
   232  		// If a template by that name exists,
   233  		// don't replace it with an empty template.
   234  		return false
   235  	}
   236  	t.tmpl[new.name] = new
   237  	return true
   238  }
   239  

View as plain text