-
Notifications
You must be signed in to change notification settings - Fork 0
/
templates.go
87 lines (73 loc) · 1.87 KB
/
templates.go
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
package internal
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"path"
"text/template"
)
// TemplateLoader loads templates from the specified name.
func (a *ArgType) TemplateLoader(name string) ([]byte, error) {
return ioutil.ReadFile(path.Join(a.TemplatePath, name))
}
// TemplateSet retrieves the created template set.
func (a *ArgType) TemplateSet() *TemplateSet {
if a.templateSet == nil {
a.templateSet = &TemplateSet{
funcs: a.NewTemplateFuncs(),
l: a.TemplateLoader,
tpls: map[string]*template.Template{},
}
}
return a.templateSet
}
// ExecuteTemplate loads and parses the supplied template with name and
// executes it with obj as the context.
func (a *ArgType) ExecuteTemplate(tt TemplateType, et EditableType, name string, obj interface{}) error {
var err error
// setup generated
if a.Generated == nil {
a.Generated = []TBuf{}
}
// create store
v := TBuf{
TemplateType: tt,
EditableType: et,
Name: name,
Buf: new(bytes.Buffer),
}
// build template name
templateName := fmt.Sprintf("%s.go.tpl", tt)
// execute template
err = a.TemplateSet().Execute(v.Buf, templateName, obj)
if err != nil {
return err
}
a.Generated = append(a.Generated, v)
return nil
}
// TemplateSet is a set of templates.
type TemplateSet struct {
funcs template.FuncMap
l func(string) ([]byte, error)
tpls map[string]*template.Template
}
// Execute executes a specified template in the template set using the supplied
// obj as its parameters and writing the output to w.
func (ts *TemplateSet) Execute(w io.Writer, name string, obj interface{}) error {
tpl, ok := ts.tpls[name]
if !ok {
// attempt to load and parse the template
buf, err := ts.l(name)
if err != nil {
return err
}
// parse template
tpl, err = template.New(name).Funcs(ts.funcs).Parse(string(buf))
if err != nil {
return err
}
}
return tpl.Execute(w, obj)
}