-
Notifications
You must be signed in to change notification settings - Fork 15
/
templates.go
executable file
·88 lines (73 loc) · 1.69 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
88
package templates
import (
"os"
"strings"
"text/template"
)
const sampleTemplate = `
This template demonstrates printing a {{ .Variable | printf "%#v" }}.
{{if .Condition}}
If condition is set, we'll print this
{{else}}
Otherwise, we'll print this instead
{{end}}
Next we'll iterate over an array of strings:
{{range $index, $item := .Items}}
{{$index}}: {{$item}}
{{end}}
We can also easily import other functions like strings.Split
then immediately used the array created as a result:
{{ range $index, $item := split .Words ","}}
{{$index}}: {{$item}}
{{end}}
Blocks are a way to embed templates into one another
{{ block "block_example" .}}
No Block defined!
{{end}}
{{/*
This is a way
to insert a multi-line comment
*/}}
`
const secondTemplate = `
{{ define "block_example" }}
{{.OtherVariable}}
{{end}}
`
func RunTemplate() error {
data := struct {
Condition bool
Variable string
Items []string
Words string
OtherVariable string
}{
Condition: true,
Variable: "variable",
Items: []string{"item1", "item2", "item3"},
Words: "another_item1,another_item2,another_item3",
OtherVariable: "I'm defined in a second template!",
}
funcmap := template.FuncMap{
"split": strings.Split,
}
t := template.New("example")
t = t.Funcs(funcmap)
t, err := t.Parse(sampleTemplate)
if err != nil {
return err
}
t2, err := t.Clone()
if err != nil {
return err
}
t2, err = t2.Parse(secondTemplate)
if err != nil {
return err
}
err = t2.Execute(os.Stdout, &data)
if err != nil {
return err
}
return nil
}