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