aboutsummaryrefslogtreecommitdiff
path: root/libgo/go/text/template/parse.go
blob: fa562141c29f28852cdd2e274f748bc633241563 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package template

import (
	"reflect"
	"text/template/parse"
)

// Template is the representation of a parsed template.
type Template struct {
	name string
	*parse.Tree
	leftDelim  string
	rightDelim string
	// We use two maps, one for parsing and one for execution.
	// This separation makes the API cleaner since it doesn't
	// expose reflection to the client.
	parseFuncs FuncMap
	execFuncs  map[string]reflect.Value
	set        *Set // can be nil.
}

// Name returns the name of the template.
func (t *Template) Name() string {
	return t.name
}

// Parsing.

// New allocates a new template with the given name.
func New(name string) *Template {
	return &Template{
		name:       name,
		parseFuncs: make(FuncMap),
		execFuncs:  make(map[string]reflect.Value),
	}
}

// Delims sets the action delimiters, to be used in a subsequent
// parse, to the specified strings.
// An empty delimiter stands for the corresponding default: {{ or }}.
// The return value is the template, so calls can be chained.
func (t *Template) Delims(left, right string) *Template {
	t.leftDelim = left
	t.rightDelim = right
	return t
}

// Funcs adds the elements of the argument map to the template's function
// map.  It panics if a value in the map is not a function with appropriate
// return type.
// The return value is the template, so calls can be chained.
func (t *Template) Funcs(funcMap FuncMap) *Template {
	addValueFuncs(t.execFuncs, funcMap)
	addFuncs(t.parseFuncs, funcMap)
	return t
}

// Parse parses the template definition string to construct an internal
// representation of the template for execution.
func (t *Template) Parse(s string) (tmpl *Template, err error) {
	t.Tree, err = parse.New(t.name).Parse(s, t.leftDelim, t.rightDelim, t.parseFuncs, builtins)
	if err != nil {
		return nil, err
	}
	return t, nil
}

// ParseInSet parses the template definition string to construct an internal
// representation of the template for execution. It also adds the template
// to the set. It is an error if s is already defined in the set.
// Function bindings are checked against those in the set.
func (t *Template) ParseInSet(s string, set *Set) (tmpl *Template, err error) {
	var setFuncs FuncMap
	if set != nil {
		setFuncs = set.parseFuncs
	}
	t.Tree, err = parse.New(t.name).Parse(s, t.leftDelim, t.rightDelim, t.parseFuncs, setFuncs, builtins)
	if err != nil {
		return nil, err
	}
	if set != nil {
		err = set.add(t)
	}
	return t, err
}