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.
14 // Set holds a set of related templates that can refer to one another by name.
15 // The zero value represents an empty set.
16 // A template may be a member of multiple sets.
18 tmpl map[string]*Template
22 execFuncs map[string]reflect.Value
25 func (s *Set) init() {
27 s.tmpl = make(map[string]*Template)
28 s.parseFuncs = make(FuncMap)
29 s.execFuncs = make(map[string]reflect.Value)
33 // Delims sets the action delimiters, to be used in a subsequent
34 // parse, to the specified strings.
35 // An empty delimiter stands for the corresponding default: {{ or }}.
36 // The return value is the set, so calls can be chained.
37 func (s *Set) Delims(left, right string) *Set {
43 // Funcs adds the elements of the argument map to the set's function map. It
44 // panics if a value in the map is not a function with appropriate return
46 // The return value is the set, so calls can be chained.
47 func (s *Set) Funcs(funcMap FuncMap) *Set {
49 addValueFuncs(s.execFuncs, funcMap)
50 addFuncs(s.parseFuncs, funcMap)
54 // Add adds the argument templates to the set. It panics if two templates
55 // with the same name are added or if a template is already a member of
57 // The return value is the set, so calls can be chained.
58 func (s *Set) Add(templates ...*Template) *Set {
59 for _, t := range templates {
60 if err := s.add(t); err != nil {
67 // add adds the argument template to the set.
68 func (s *Set) add(t *Template) error {
71 return fmt.Errorf("template: %q already in a set", t.name)
73 if _, ok := s.tmpl[t.name]; ok {
74 return fmt.Errorf("template: %q already defined in set", t.name)
81 // Template returns the template with the given name in the set,
82 // or nil if there is no such template.
83 func (s *Set) Template(name string) *Template {
87 // FuncMap returns the set's function map.
88 func (s *Set) FuncMap() FuncMap {
92 // Execute applies the named template to the specified data object, writing
94 func (s *Set) Execute(wr io.Writer, name string, data interface{}) error {
97 return fmt.Errorf("template: no template %q in set", name)
99 return tmpl.Execute(wr, data)
102 // Parse parses a string into a set of named templates. Parse may be called
103 // multiple times for a given set, adding the templates defined in the string
104 // to the set. It is an error if a template has a name already defined in the set.
105 func (s *Set) Parse(text string) (*Set, error) {
106 trees, err := parse.Set(text, s.leftDelim, s.rightDelim, s.parseFuncs, builtins)
111 for name, tree := range trees {