diff options
author | Ondřej Surý <ondrej@sury.org> | 2012-01-30 15:38:19 +0100 |
---|---|---|
committer | Ondřej Surý <ondrej@sury.org> | 2012-01-30 15:38:19 +0100 |
commit | 4cecda6c347bd6902b960c6a35a967add7070b0d (patch) | |
tree | a462e224ff41ec9f3eb1a0b6e815806f9e8804ad /src/pkg/text/template/example_test.go | |
parent | 6c7ca6e4d4e26e4c8cbe0d183966011b3b088a0a (diff) | |
download | golang-4cecda6c347bd6902b960c6a35a967add7070b0d.tar.gz |
Imported Upstream version 2012.01.27upstream-weekly/2012.01.27
Diffstat (limited to 'src/pkg/text/template/example_test.go')
-rw-r--r-- | src/pkg/text/template/example_test.go | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/src/pkg/text/template/example_test.go b/src/pkg/text/template/example_test.go new file mode 100644 index 000000000..b7701ea26 --- /dev/null +++ b/src/pkg/text/template/example_test.go @@ -0,0 +1,69 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package template_test + +import ( + "log" + "os" + "text/template" +) + +// Dear Aunt Mildred, +// +// It was a pleasure to see you at the wedding. +// Thank you for the lovely bone china tea set. +// +// Best wishes, +// Josie +// +// Dear Uncle John, +// +// It is a shame you couldn't make it to the wedding. +// Thank you for the lovely moleskin pants. +// +// Best wishes, +// Josie +// +// Dear Cousin Rodney, +// +// It is a shame you couldn't make it to the wedding. +// +// Best wishes, +// Josie +func ExampleTemplate() { + // Define a template. + 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 +` + + // Prepare some data to insert into the template. + 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}, + } + + // Create a new template and parse the letter into it. + t := template.Must(template.New("letter").Parse(letter)) + + // Execute the template for each recipient. + for _, r := range recipients { + err := t.Execute(os.Stdout, r) + if err != nil { + log.Println("executing template:", err) + } + } +} |