...
1
2
3
4
5 package template_test
6
7 import (
8 "log"
9 "os"
10 "strings"
11 "text/template"
12 )
13
14 func ExampleTemplate() {
15
16 const letter = `
17 Dear {{.Name}},
18 {{if .Attended}}
19 It was a pleasure to see you at the wedding.
20 {{- else}}
21 It is a shame you couldn't make it to the wedding.
22 {{- end}}
23 {{with .Gift -}}
24 Thank you for the lovely {{.}}.
25 {{end}}
26 Best wishes,
27 Josie
28 `
29
30
31 type Recipient struct {
32 Name, Gift string
33 Attended bool
34 }
35 var recipients = []Recipient{
36 {"Aunt Mildred", "bone china tea set", true},
37 {"Uncle John", "moleskin pants", false},
38 {"Cousin Rodney", "", false},
39 }
40
41
42 t := template.Must(template.New("letter").Parse(letter))
43
44
45 for _, r := range recipients {
46 err := t.Execute(os.Stdout, r)
47 if err != nil {
48 log.Println("executing template:", err)
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 func ExampleTemplate_block() {
80 const (
81 master = `Names:{{block "list" .}}{{"\n"}}{{range .}}{{println "-" .}}{{end}}{{end}}`
82 overlay = `{{define "list"}} {{join . ", "}}{{end}} `
83 )
84 var (
85 funcs = template.FuncMap{"join": strings.Join}
86 guardians = []string{"Gamora", "Groot", "Nebula", "Rocket", "Star-Lord"}
87 )
88 masterTmpl, err := template.New("master").Funcs(funcs).Parse(master)
89 if err != nil {
90 log.Fatal(err)
91 }
92 overlayTmpl, err := template.Must(masterTmpl.Clone()).Parse(overlay)
93 if err != nil {
94 log.Fatal(err)
95 }
96 if err := masterTmpl.Execute(os.Stdout, guardians); err != nil {
97 log.Fatal(err)
98 }
99 if err := overlayTmpl.Execute(os.Stdout, guardians); err != nil {
100 log.Fatal(err)
101 }
102
103
104
105
106
107
108
109
110 }
111
View as plain text