To turn a slice into repeated HTML, put a range action around the markup for one item: `{{ range . }}<li>{{ . }}</li>{{ end }}`. The dot (`.`) initially holds the value passed to template execution; inside this range, it holds each element in turn. `{{ end }}` closes the repeated block. section 11.2.1
Choose the form that matches what the markup needs:
- `{{ range $index, $value := . }} ... {{ end }}` binds an index and an element for use within the block. For a map, the two variables hold a key and value. section 11.2.1 section 11.6
- `{{ range . }} ... {{ end }}` needs no named variables: dot becomes each element or map value. Unlike Go’s `for x := range values`, it does not make dot the index or key. section 11.2.1
Render numbered list items
Pass `[]int{47, 52, 88, 18}` with `tpl.Execute(w, values)`. In the HTML template, `<li>{{ $index }} : {{ $value }}</li>` inside `{{ range $index, $value := . }}` renders each number with its index. section 11.2.1
Listing 11.23 index.html: Unordered list in the template
<ul>
{{ range $index, $value := . }} #1
<li>{{ $index }} : {{ $value }}</li>
{{ end }}
</ul>
A complete unordered-list template shows where the range block opens, how its variables appear in an item, and where it ends. section 11.2.1
A range can sit inside other template control flow. When execution data contains a `Habits` field, `{{ if .Habits }}` can guard the list while `{{ range .Habits }}` repeats its items. Range accepts slices, arrays, maps, and channels. section 11.5.1 section 11.6
