Sunday, September 18, 2011

Go Template Examples

The Go language's template package has introduced a set of new APIs in r60. (To keep using the old template package, you'll need to change import "template" to import "old/template".) This post includes a collection of code snippets to illustrate how to use the new template package.

Parse a template string

t, _ := template.New("template_name").Parse("Go")
t.Execute(os.Stdout, nil)

// output: Go

Parse a template file

t, _ := template.New("template_name").ParseFile("external.file")
t.Execute(os.Stdout, nil)

// output: content of external.file

Print to a string buffer

t, _ := template.New("template_name").Parse("Go")
buf := new(bytes.Buffer)
t.Execute(buf, nil)

// buf.String() == "Go"

Substitute a single parameter

t, _ := template.New("template_name").Parse("<h1>{{.}}</h1>")
t.Execute(os.Stdout, "Joseki")

// output: <h1>Joseki</h1>

Substitute multiple parameters in a struct

type dict struct {
  // struct fields must be public
  Title string
  Release int
}
params := &dict{Title: "Go", Release: 60}
t, _ := template.New("template_name").Parse(
    "<h1>{{.Title}}</h1>r{{.Release}}")
t.Execute(os.Stdout, params)

// output: <h1>Go</h1>r60

Substitute multiple parameters in a map

t, _ := template.New("template_name").Parse(
    "<h1>{{.title}}</h1>r{{.release}}")
// field names don't have to be capitalized
params := map[string]interface{}{"title": "Go", "release": 60}
t.Execute(os.Stdout, params)

// output: <h1>Go</h1>r60

Conditionally fill in parameters

t, _ := template.New("template_name").Parse(
    "{{if .white}}Gote{{else}}Sente{{end}}{{if .excl}}!{{end}}")
t.Execute(os.Stdout, map[string]bool{"excl": true})

// output: Sente!

Iteratively fill in parameters

t, _ := template.New("template_name").Parse(
    "{{range .}}{{.}}!{{else}}Tengen{{end}}")
t.Execute(os.Stdout, [...]string{"Hoshi", "Komoku", "Sansan"})

// output: Hoshi!Komoku!Sansan!

Escape parameters

t, _ := template.New("html").Parse(
    "<a href='/?q={{.query | urlquery}}'>q={{.text | html}}</a>")
t.Execute(os.Stdout, map[string]string{"text": "&", "query": "&"})

// output: <a href='/?q=%26'>q=&amp;</a>

Nest templates

ts := new(template.Set)
tparent, _ := template.New("parent").Parse(
    "<i>{{template \"child\" .}}</i>")
tchild, _ := template.New("child").Parse(
    "<b>{{.lang}}</b>")
ts.Add(tparent, tchild)
ts.Execute(os.Stdout, "parent", map[string]string{"lang": "Go"})

// output: <i><b>Go</b></i>

Parse a template set

ts := new(template.Set)
ts.Parse(`{{define "parent"}}<i>{{template "child" .}}</i>{{end}}
    {{define "child"}}<b>{{.lang}}</b>{{end}}`)
ts.Execute(os.Stdout, "parent", map[string]string{"lang": "Go"})

// output: <i><b>Go</b></i>

The template package also offers a few more APIs not covered by the examples. Please refer to the documentation for more information.

No comments:

Post a Comment