| | |
| | |
| | |
| |
|
| | package template_test |
| |
|
| | import ( |
| | "log" |
| | "os" |
| | "strings" |
| | "text/template" |
| | ) |
| |
|
| | func ExampleTemplate() { |
| | |
| | const letter = ` |
| | Dear {{.Name}}, |
| | {{if .Attended}} |
| | It was a pleasure to see you at the wedding. |
| | {{- else}} |
| | It is a shame you couldn't make it to the wedding. |
| | {{- end}} |
| | {{with .Gift -}} |
| | Thank you for the lovely {{.}}. |
| | {{end}} |
| | Best wishes, |
| | Josie |
| | ` |
| |
|
| | |
| | type Recipient struct { |
| | Name, Gift string |
| | Attended bool |
| | } |
| | var recipients = []Recipient{ |
| | {"Aunt Mildred", "bone china tea set", true}, |
| | {"Uncle John", "moleskin pants", false}, |
| | {"Cousin Rodney", "", false}, |
| | } |
| |
|
| | |
| | t := template.Must(template.New("letter").Parse(letter)) |
| |
|
| | |
| | for _, r := range recipients { |
| | err := t.Execute(os.Stdout, r) |
| | if err != nil { |
| | log.Println("executing template:", err) |
| | } |
| | } |
| |
|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | } |
| |
|
| | |
| |
|
| | func ExampleTemplate_block() { |
| | const ( |
| | master = `Names:{{block "list" .}}{{"\n"}}{{range .}}{{println "-" .}}{{end}}{{end}}` |
| | overlay = `{{define "list"}} {{join . ", "}}{{end}} ` |
| | ) |
| | var ( |
| | funcs = template.FuncMap{"join": strings.Join} |
| | guardians = []string{"Gamora", "Groot", "Nebula", "Rocket", "Star-Lord"} |
| | ) |
| | masterTmpl, err := template.New("master").Funcs(funcs).Parse(master) |
| | if err != nil { |
| | log.Fatal(err) |
| | } |
| | overlayTmpl, err := template.Must(masterTmpl.Clone()).Parse(overlay) |
| | if err != nil { |
| | log.Fatal(err) |
| | } |
| | if err := masterTmpl.Execute(os.Stdout, guardians); err != nil { |
| | log.Fatal(err) |
| | } |
| | if err := overlayTmpl.Execute(os.Stdout, guardians); err != nil { |
| | log.Fatal(err) |
| | } |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | } |
| |
|