+43
Go/templates/main.go
+43
Go/templates/main.go
···
1
+
package main
2
+
3
+
import (
4
+
"bytes"
5
+
"fmt"
6
+
"text/template"
7
+
)
8
+
9
+
const letter = `Dear {{.Name}},
10
+
{{if .Attended}}
11
+
It was a pleasure to see you at the wedding.
12
+
{{- else}}
13
+
It is a shame you couldn't make it to the wedding.
14
+
{{- end}}
15
+
Best wishes,
16
+
Alex`
17
+
18
+
func main() {
19
+
people := []struct {
20
+
Name string
21
+
Attended bool
22
+
}{
23
+
{
24
+
Name: "Alex",
25
+
Attended: true,
26
+
},
27
+
{
28
+
Name: "Mick",
29
+
Attended: false,
30
+
},
31
+
}
32
+
33
+
t := template.Must(template.New("letter").Parse(letter))
34
+
35
+
for _, person := range people {
36
+
buffer := bytes.Buffer{}
37
+
err := t.Execute(&buffer, person)
38
+
if err != nil {
39
+
panic(err)
40
+
}
41
+
fmt.Printf("Letter for %s:\n\n%s\n\n", person.Name, buffer.String())
42
+
}
43
+
}