Source file
src/text/template/examplefunc_test.go
1
2
3
4
5 package template_test
6
7 import (
8 "log"
9 "os"
10 "strings"
11 "text/template"
12 )
13
14
15
16
17 func ExampleTemplate_func() {
18
19 funcMap := template.FuncMap{
20
21 "title": strings.Title,
22 }
23
24
25
26
27
28
29
30 const templateText = `
31 Input: {{printf "%q" .}}
32 Output 0: {{title .}}
33 Output 1: {{title . | printf "%q"}}
34 Output 2: {{printf "%q" . | title}}
35 `
36
37
38 tmpl, err := template.New("titleTest").Funcs(funcMap).Parse(templateText)
39 if err != nil {
40 log.Fatalf("parsing: %s", err)
41 }
42
43
44 err = tmpl.Execute(os.Stdout, "the go programming language")
45 if err != nil {
46 log.Fatalf("execution: %s", err)
47 }
48
49
50
51
52
53
54 }
55
56
57
58
59
60 func ExampleTemplate_funcs() {
61
62
63 const tmpl = `{{ . | lower | repeat }}`
64
65
66 var funcMap = template.FuncMap{
67 "lower": strings.ToLower,
68 "repeat": func(s string) string { return strings.Repeat(s, 2) },
69 }
70
71
72
73 parsedTmpl, err := template.New("t").Funcs(funcMap).Parse(tmpl)
74 if err != nil {
75 log.Fatal(err)
76 }
77 if err := parsedTmpl.Execute(os.Stdout, "ABC\n"); err != nil {
78 log.Fatal(err)
79 }
80
81
82
83
84
85
86 parsedTmpl.Funcs(template.FuncMap{
87 "repeat": func(s string) string { return strings.Repeat(s, 3) },
88 })
89 if err := parsedTmpl.Execute(os.Stdout, "DEF\n"); err != nil {
90 log.Fatal(err)
91 }
92
93
94
95
96
97
98 }
99
100
101 func ExampleTemplate_if() {
102 type book struct {
103 Stars float32
104 Name string
105 }
106
107 tpl, err := template.New("book").Parse(`{{ if (gt .Stars 4.0) }}"{{.Name }}" is a great book.{{ else }}"{{.Name}}" is not a great book.{{ end }}`)
108 if err != nil {
109 log.Fatalf("failed to parse template: %s", err)
110 }
111
112 b := &book{
113 Stars: 4.9,
114 Name: "Good Night, Gopher",
115 }
116 err = tpl.Execute(os.Stdout, b)
117 if err != nil {
118 log.Fatalf("failed to execute template: %s", err)
119 }
120
121
122
123 }
124
View as plain text