github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/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 "github.com/shogo82148/std/log" 9 "github.com/shogo82148/std/os" 10 "github.com/shogo82148/std/strings" 11 "github.com/shogo82148/std/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 // テンプレートに挿入するためのデータを準備します。 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 // 新しいテンプレートを作成し、その中にレターを解析します。 42 t := template.Must(template.New("letter").Parse(letter)) 43 44 // 各受信者に対してテンプレートを実行します。 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 func ExampleTemplate_block() { 78 const ( 79 master = `Names:{{block "list" .}}{{"\n"}}{{range .}}{{println "-" .}}{{end}}{{end}}` 80 overlay = `{{define "list"}} {{join . ", "}}{{end}} ` 81 ) 82 var ( 83 funcs = template.FuncMap{"join": strings.Join} 84 guardians = []string{"Gamora", "Groot", "Nebula", "Rocket", "Star-Lord"} 85 ) 86 masterTmpl, err := template.New("master").Funcs(funcs).Parse(master) 87 if err != nil { 88 log.Fatal(err) 89 } 90 overlayTmpl, err := template.Must(masterTmpl.Clone()).Parse(overlay) 91 if err != nil { 92 log.Fatal(err) 93 } 94 if err := masterTmpl.Execute(os.Stdout, guardians); err != nil { 95 log.Fatal(err) 96 } 97 if err := overlayTmpl.Execute(os.Stdout, guardians); err != nil { 98 log.Fatal(err) 99 } 100 // Output: 101 // Names: 102 // - Gamora 103 // - Groot 104 // - Nebula 105 // - Rocket 106 // - Star-Lord 107 // Names: Gamora, Groot, Nebula, Rocket, Star-Lord 108 }