Created
March 10, 2016 08:57
-
-
Save xigang/8c71d1ed06f7e7b1e183 to your computer and use it in GitHub Desktop.
golang 模板示例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"os" | |
"text/template" | |
) | |
func main() { | |
// 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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment