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
5package template_test
6
7import (
8	"log"
9	"os"
10
11	"github.com/alecthomas/template"
12)
13
14func ExampleTemplate() {
15	// Define a template.
16	const letter = `
17Dear {{.Name}},
18{{if .Attended}}
19It was a pleasure to see you at the wedding.{{else}}
20It is a shame you couldn't make it to the wedding.{{end}}
21{{with .Gift}}Thank you for the lovely {{.}}.
22{{end}}
23Best wishes,
24Josie
25`
26
27	// Prepare some data to insert into the template.
28	type Recipient struct {
29		Name, Gift string
30		Attended   bool
31	}
32	var recipients = []Recipient{
33		{"Aunt Mildred", "bone china tea set", true},
34		{"Uncle John", "moleskin pants", false},
35		{"Cousin Rodney", "", false},
36	}
37
38	// Create a new template and parse the letter into it.
39	t := template.Must(template.New("letter").Parse(letter))
40
41	// Execute the template for each recipient.
42	for _, r := range recipients {
43		err := t.Execute(os.Stdout, r)
44		if err != nil {
45			log.Println("executing template:", err)
46		}
47	}
48
49	// Output:
50	// Dear Aunt Mildred,
51	//
52	// It was a pleasure to see you at the wedding.
53	// Thank you for the lovely bone china tea set.
54	//
55	// Best wishes,
56	// Josie
57	//
58	// Dear Uncle John,
59	//
60	// It is a shame you couldn't make it to the wedding.
61	// Thank you for the lovely moleskin pants.
62	//
63	// Best wishes,
64	// Josie
65	//
66	// Dear Cousin Rodney,
67	//
68	// It is a shame you couldn't make it to the wedding.
69	//
70	// Best wishes,
71	// Josie
72}
73