github.com/mdempsky/go@v0.0.0-20151201204031-5dd372bd1e70/src/text/template/example_test.go (about) 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 "strings" 11 "text/template" 12 ) 13 14 func ExampleTemplate() { 15 // Define a template. 16 const letter = ` 17 Dear {{.Name}}, 18 {{if .Attended}} 19 It was a pleasure to see you at the wedding. 20 {{- else}} 21 It is a shame you couldn't make it to the wedding. 22 {{- end}} 23 {{with .Gift -}} 24 Thank you for the lovely {{.}}. 25 {{end}} 26 Best wishes, 27 Josie 28 ` 29 30 // Prepare some data to insert into the template. 31 type Recipient struct { 32 Name, Gift string 33 Attended bool 34 } 35 var recipients = []Recipient{ 36 {"Aunt Mildred", "bone china tea set", true}, 37 {"Uncle John", "moleskin pants", false}, 38 {"Cousin Rodney", "", false}, 39 } 40 41 // Create a new template and parse the letter into it. 42 t := template.Must(template.New("letter").Parse(letter)) 43 44 // Execute the template for each recipient. 45 for _, r := range recipients { 46 err := t.Execute(os.Stdout, r) 47 if err != nil { 48 log.Println("executing template:", err) 49 } 50 } 51 52 // Output: 53 // Dear Aunt Mildred, 54 // 55 // It was a pleasure to see you at the wedding. 56 // Thank you for the lovely bone china tea set. 57 // 58 // Best wishes, 59 // Josie 60 // 61 // Dear Uncle John, 62 // 63 // It is a shame you couldn't make it to the wedding. 64 // Thank you for the lovely moleskin pants. 65 // 66 // Best wishes, 67 // Josie 68 // 69 // Dear Cousin Rodney, 70 // 71 // It is a shame you couldn't make it to the wedding. 72 // 73 // Best wishes, 74 // Josie 75 } 76 77 // The following example is duplicated in html/template; keep them in sync. 78 79 func ExampleTemplate_block() { 80 const ( 81 master = `Names:{{block "list" .}}{{"\n"}}{{range .}}{{println "-" .}}{{end}}{{end}}` 82 overlay = `{{define "list"}} {{join . ", "}}{{end}} ` 83 ) 84 var ( 85 funcs = template.FuncMap{"join": strings.Join} 86 guardians = []string{"Gamora", "Groot", "Nebula", "Rocket", "Star-Lord"} 87 ) 88 masterTmpl, err := template.New("master").Funcs(funcs).Parse(master) 89 if err != nil { 90 log.Fatal(err) 91 } 92 overlayTmpl, err := template.Must(masterTmpl.Clone()).Parse(overlay) 93 if err != nil { 94 log.Fatal(err) 95 } 96 if err := masterTmpl.Execute(os.Stdout, guardians); err != nil { 97 log.Fatal(err) 98 } 99 if err := overlayTmpl.Execute(os.Stdout, guardians); err != nil { 100 log.Fatal(err) 101 } 102 // Output: 103 // Names: 104 // - Gamora 105 // - Groot 106 // - Nebula 107 // - Rocket 108 // - Star-Lord 109 // Names: Gamora, Groot, Nebula, Rocket, Star-Lord 110 }