Skip to content

Commit 0bb8ce2

Browse files
committed
text/template: add example for Template
R=golang-dev, r CC=golang-dev https://golang.org/cl/5564050
1 parent 2c2c202 commit 0bb8ce2

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

src/pkg/text/template/example_test.go

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
// Copyright 2011 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
package template_test
6+
7+
import (
8+
"log"
9+
"os"
10+
"text/template"
11+
)
12+
13+
// Dear Aunt Mildred,
14+
//
15+
// It was a pleasure to see you at the wedding.
16+
// Thank you for the lovely bone china tea set.
17+
//
18+
// Best wishes,
19+
// Josie
20+
//
21+
// Dear Uncle John,
22+
//
23+
// It is a shame you couldn't make it to the wedding.
24+
// Thank you for the lovely moleskin pants.
25+
//
26+
// Best wishes,
27+
// Josie
28+
//
29+
// Dear Cousin Rodney,
30+
//
31+
// It is a shame you couldn't make it to the wedding.
32+
//
33+
// Best wishes,
34+
// Josie
35+
func ExampleTemplate() {
36+
// Define a template.
37+
const letter = `
38+
Dear {{.Name}},
39+
{{if .Attended}}
40+
It was a pleasure to see you at the wedding.{{else}}
41+
It is a shame you couldn't make it to the wedding.{{end}}
42+
{{with .Gift}}Thank you for the lovely {{.}}.
43+
{{end}}
44+
Best wishes,
45+
Josie
46+
`
47+
48+
// Prepare some data to insert into the template.
49+
type Recipient struct {
50+
Name, Gift string
51+
Attended bool
52+
}
53+
var recipients = []Recipient{
54+
{"Aunt Mildred", "bone china tea set", true},
55+
{"Uncle John", "moleskin pants", false},
56+
{"Cousin Rodney", "", false},
57+
}
58+
59+
// Create a new template and parse the letter into it.
60+
t := template.Must(template.New("letter").Parse(letter))
61+
62+
// Execute the template for each recipient.
63+
for _, r := range recipients {
64+
err := t.Execute(os.Stdout, r)
65+
if err != nil {
66+
log.Println("executing template:", err)
67+
}
68+
}
69+
}

0 commit comments

Comments
 (0)