If, with and range
View as MarkdownEach block closes with {{end}}. A value is false when it is false, 0,
nil, an empty string, array, object, Map or Set, or no value at all.
Everything else is true.
if #
{{if .error}}Failed: {{.error}}{{else if .done}}Done{{else}}Working{{end}}
if runs its body when the pipeline is true. else if and else are
optional. Dot stays the same.
with #
{{with .user}}Signed in as {{.name}}{{else}}Signed out{{end}}
with runs its body when the pipeline is true, with dot set to the value.
else with tries another value:
{{with .nickname}}{{.}}{{else with .name}}{{.}}{{else}}Guest{{end}}
range #
{{range .items}}<li>{{.}}</li>{{else}}<li>None</li>{{end}}
range runs its body once per element, with dot set to it. else runs when
there are none. It walks:
| Value | Gives |
|---|---|
| array, typed array | each element, with its index |
plain object, Map |
each value, with its key |
a number n |
0 to n - 1 |
Set, generator, iterable |
each value, without a key |
Name the index or key, and the element, with two variables:
{{range $i, $item := .items}}{{$i}}: {{$item}}
{{end}}
One variable takes the element: {{range $item := .items}}.
obol walks an object or Map in its own order. Go sorts map keys; see
Differences.
break and continue #
{{range .}}{{if eq . 3}}{{break}}{{end}}{{if eq . 1}}{{continue}}{{end}}{{.}}{{end}}
Given [0, 1, 2, 3, 4], that prints 02. {{break}} ends the loop, and
{{continue}} skips to the next element. Both work only inside range.