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