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