-
Notifications
You must be signed in to change notification settings - Fork 110
/
template.go
53 lines (47 loc) · 1.12 KB
/
template.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
package generate
import (
"embed"
"io"
"strings"
"text/template"
)
//go:embed *.tmpl
var templates embed.FS
func repeat(n int, s string) string {
var builder strings.Builder
for i := 0; i < n; i++ {
builder.WriteString(s)
}
return builder.String()
}
func intRange(n int) []int {
ret := make([]int, n)
for i := 0; i < n; i++ {
ret[i] = i
}
return ret
}
func sub(x, y int) int { return x - y }
// render executes the given template with the funcs from this generator.
func (g *generator) render(tmplRelFilename string, w io.Writer, data interface{}) error {
tmpl := g.templateCache[tmplRelFilename]
if tmpl == nil {
funcMap := template.FuncMap{
"ref": g.ref,
"repeat": repeat,
"intRange": intRange,
"sub": sub,
}
var err error
tmpl, err = template.New(tmplRelFilename).Funcs(funcMap).ParseFS(templates, tmplRelFilename)
if err != nil {
return errorf(nil, "could not load template %v: %v", tmplRelFilename, err)
}
g.templateCache[tmplRelFilename] = tmpl
}
err := tmpl.Execute(w, data)
if err != nil {
return errorf(nil, "could not render template: %v", err)
}
return nil
}