|
| 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