liveBook · Manning

Range clause

As explained in Learn Go with Pocket-Sized Projects

A range action is a Go template directive that iterates over a rangeable value and optionally binds an index or key and an element value within a scoped block.

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

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Works through index-and-value bindings and dot-based iteration, stopping short of template-engine internals.
Examples
Renders an integer slice as an indexed HTML list and nests a habits list inside an if action.
What it assumes
Assumes familiarity with Go slices and template execution while introducing range-action syntax through a small example.
What you can do after
Apply it via Go HTML templates to repeat markup, optionally displaying each item's index or key.
How it connects
Connects template execution, dot, Go for-range loops, and conditional template actions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.