Chapter 16 - HTML Templates

Exercise 1: A Text Template

Set the templateText variable so that the program will produce the output shown.

Output:

- apples
- oranges
- pears
- chicken
- beef
- lamb

Solution

package main

import (
	"log"
	"os"
	"text/template"
)

func check(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

func executeTemplate(templateText string, data interface{}) {
	tmpl, err := template.New("template").Parse(templateText)
	check(err)
	err = tmpl.Execute(os.Stdout, data)
	check(err)
}

func main() {
	templateText := "{{range .}}- {{.}}\n{{end}}"
	executeTemplate(templateText,
		[]string{"apples", "oranges", "pears"})
	executeTemplate(templateText,
		[]string{"chicken", "beef", "lamb"})
}