Home | History | Annotate | Download | only in template
      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 	"log"
      9 	"os"
     10 	"text/template"
     11 )
     12 
     13 func ExampleTemplate() {
     14 	// Define a template.
     15 	const letter = `
     16 Dear {{.Name}},
     17 {{if .Attended}}
     18 It was a pleasure to see you at the wedding.{{else}}
     19 It is a shame you couldn't make it to the wedding.{{end}}
     20 {{with .Gift}}Thank you for the lovely {{.}}.
     21 {{end}}
     22 Best wishes,
     23 Josie
     24 `
     25 
     26 	// Prepare some data to insert into the template.
     27 	type Recipient struct {
     28 		Name, Gift string
     29 		Attended   bool
     30 	}
     31 	var recipients = []Recipient{
     32 		{"Aunt Mildred", "bone china tea set", true},
     33 		{"Uncle John", "moleskin pants", false},
     34 		{"Cousin Rodney", "", false},
     35 	}
     36 
     37 	// Create a new template and parse the letter into it.
     38 	t := template.Must(template.New("letter").Parse(letter))
     39 
     40 	// Execute the template for each recipient.
     41 	for _, r := range recipients {
     42 		err := t.Execute(os.Stdout, r)
     43 		if err != nil {
     44 			log.Println("executing template:", err)
     45 		}
     46 	}
     47 
     48 	// Output:
     49 	// Dear Aunt Mildred,
     50 	//
     51 	// It was a pleasure to see you at the wedding.
     52 	// Thank you for the lovely bone china tea set.
     53 	//
     54 	// Best wishes,
     55 	// Josie
     56 	//
     57 	// Dear Uncle John,
     58 	//
     59 	// It is a shame you couldn't make it to the wedding.
     60 	// Thank you for the lovely moleskin pants.
     61 	//
     62 	// Best wishes,
     63 	// Josie
     64 	//
     65 	// Dear Cousin Rodney,
     66 	//
     67 	// It is a shame you couldn't make it to the wedding.
     68 	//
     69 	// Best wishes,
     70 	// Josie
     71 }
     72