liveBook · Manning

With action

As explained in Learn Go with Pocket-Sized Projects

A with action is a template control-flow action that conditionally changes the current dot to a specified value within a block.

A with action temporarily changes the template’s current dot to a specified value inside a block. This shortens repeated accessors and keeps the block focused on one part of the input. section 11.5.1 section 11.6

Use {{with .Date}} ... {{end}} to make .Date the local dot. Fields and methods then use shorter names such as .Start and .End; after {{end}}, the original dot is restored. section 11.5.1 section 11.6

Restrict a date display to its local value

Without a with action: <p>This period covers {{.Date.Start}} -> {{.Date.End}}.</p>\n\nWith a with action: {{with .Date}}<p>This period covers {{.Start}} -> {{.End}}.</p>{{end}}

Apply the action when:

  • A template receives several values through a map, such as Habits and Date, and one block repeatedly accesses a nested value. section 11.5.1
  • A conditional block should render only when its selected value is present; use if separately when hiding an empty habits list. section 11.5.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains syntax, dot rebinding, and scoped accessors, but does not descend into template execution internals.
Examples
Uses a Date value with Start and End accessors, alongside Habits and empty-list rendering.
What it assumes
Assumes familiarity with template actions and the dot while clarifying how blocks change the current value.
What you can do after
Apply it via Go templates to write shorter, locally scoped accessors for nested template data.
How it connects
Connects with Go templates, the dot, fields, methods, range actions, and if actions.

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.