liveBook · Manning

Template dot

As explained in Learn Go with Pocket-Sized Projects

The dot operator in Go templates denotes the current data value passed to the template or action.

In a Go template, dot (`.`) is the current data value. Pass a value to `Execute`, then place `{{ . }}` where it should appear in the output. For example, `tpl.Execute(w, 5)` makes `<p>You have {{ . }} habits to follow.</p>` render with `5` in place of the action. `{{.}}` and `{{ . }}` behave identically. section 11.1.2

Listing 11.25 index.html: Accessing fields
<ul>
    {{- range .}} #1
    <li>
        <b>{{ .Name }}</b> - {{ .WeeklyFrequency }} #2
➥time(s) a week
    </li>
    {{- end}}
</ul>

The habit-list template shows dot changing inside `range`: `{{ range . }}` iterates over the supplied slice, while `{{ .Name }}` and `{{ .WeeklyFrequency }}` read fields of the current habit. section 11.2.2

Dot changes with the action around it:

  • Use `{{ .Field }}` to read an exposed field of the current value. Field names in the template must match those exposed by the Go value. section 11.2.2
  • Use `{{ range . }}` to make each element the current dot within the loop. section 11.2.2
  • Use `{{ with .Date }}` to make `.Date` the dot within that block: `.Date.Start` becomes `.Start` there. section 11.5.1

Pass habits and a week together

`Execute` accepts one data value. Pass `map[string]interface{}{"Habits": habits, "Date": week}` to make the map the initial dot. The template can then use `{{ range .Habits }}` for the list and `{{ with .Date }}{{ .Start }} -> {{ .End }}{{ end }}` for the period. If the list should disappear when empty, wrap it in `{{ if .Habits }} ... {{ end }}`. section 11.5.1

Templates can also read eligible exposed methods with `{{ .Method }}`, without parentheses. Such methods take no arguments and return a value, optionally followed by an error. Avoid long field-and-method chains; they make templates harder to read. section 11.2.2

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Works through initial output, field access, and changes to dot inside range and with actions.
Examples
Shows a habit count, a ranged habit list, and a map containing habits and week dates.
What it assumes
Assumes Go values such as structs, slices, and maps while introducing template actions and dot from their first use.
What you can do after
Apply it via Go templates to render values and adjust field access when actions change the current dot.
How it connects
Connects dot to Go template actions, Execute, exposed fields, methods, range, with, and if.

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.