Essential Go Text and HTML templates  Suggest an edit

Built-in functions

Templating engine supports calling functions like {{ len .Tweet }} where len is a function that returns length of an array or slice.

and, or, not

and, or, not are for logical operations:

const tmplStr = `Or:  {{ if or .True .False }}true{{ else }}false{{ end }}
And: {{ if and .True .False }}true{{ else }}false{{ end }}
Not: {{ if not .False }}true{{ else }}false{{ end }}
`

t := template.Must(template.New("and_or_not").Parse(tmplStr))

data := Data{True: true, False: false}

err := t.Execute(os.Stdout, data)
if err != nil {
	log.Fatalf("t.Execute() failed with '%s'\n", err)
}
Or:  true
And: false
Not: true

index

index is for accessing elements of a slice by index or values in a map by key.

const tmplStr = `Slice[0]: {{ index .Slice 0 }}
SliceNested[1][0]: {{ index .SliceNested 1 0 }}
Map["key"]: {{ index .Map "key" }}
`

t := template.Must(template.New("index").Parse(tmplStr))

data := struct {
	Slice       []string
	SliceNested [][]int
	Map         map[string]int
}{
	Slice: []string{"first", "second"},
	SliceNested: [][]int{
		{3, 1},
		{2, 3},
	},
	Map: map[string]int{
		"key": 5,
	},
}
err := t.Execute(os.Stdout, data)
if err != nil {
	log.Fatalf("t.Execute() failed with '%s'\n", err)
}
Slice[0]: first
SliceNested[1][0]: 2
Map["key"]: 5

len

len returns length of an array of map.

const tmplStr = `len(nil)       : {{ len .SliceNil }}
len(emptySlice): {{ len .SliceEmpty }}
len(slice)     : {{ len .Slice }}
len(map)       : {{ len .Map }}
`

t := template.Must(template.New("len").Parse(tmplStr))

data := struct {
	SliceNil   []int
	SliceEmpty []string
	Slice      []bool
	Map        map[int]bool
}{
	SliceNil:   nil,
	SliceEmpty: []string{},
	Slice:      []bool{true, true, false},
	Map:        map[int]bool{5: true, 3: false},
}
err := t.Execute(os.Stdout, data)
if err != nil {
	log.Fatalf("t.Execute() failed with '%s'\n", err)
}
len(nil)       : 0
len(emptySlice): 0
len(slice)     : 3
len(map)       : 2

print, printf, println

print is like fmt.Sprint.

printf is like fmt.Sprintf.

println is like fmt.Sprintln.

const tmplStr = `print:   {{ print .Str .Num }}
println: {{ println .Str .Num }}
printf:  {{ printf "%s %#v %d" .Str .Str .Num }}
`

t := template.Must(template.New("print").Parse(tmplStr))

data := struct {
	Str string
	Num int
}{
	Str: "str",
	Num: 8,
}
err := t.Execute(os.Stdout, data)
if err != nil {
	log.Fatalf("t.Execute() failed with '%s'\n", err)
}
print:   str8
println: str 8

printf:  str "str" 8

js, html, urlquery

js, html and urlquery is for escaping text so that it can be safely inserted in a JavaScript, HTML and URL context:

const tmplStr = `js escape  : {{ js .JS }}
html escape: {{ html .HTML }}
url escape : {{ urlquery .URL }}
`

t := template.Must(template.New("print").Parse(tmplStr))

data := struct {
	JS   string
	HTML string
	URL  string
}{
	JS:   `function me(s) { return "foo"; }`,
	HTML: `<div>text</div>`,
	URL:  `http://www.programming-books.io`,
}
err := t.Execute(os.Stdout, data)
if err != nil {
	log.Fatalf("t.Execute() failed with '%s'\n", err)
}
js escape  : function me(s) { return \"foo\"; }
html escape: &lt;div&gt;text&lt;/div&gt;
url escape : http%3A%2F%2Fwww.programming-books.io
  ↑ ↓ to navigate     ↵ to select     Esc to close