liveBook · Manning

Template action

As explained in Learn Go with Pocket-Sized Projects

A template action is a delimited instruction in a template that evaluates data, control flow, definitions, or function calls.

A template action is a delimited instruction written as {{...}}. During execution, the template engine evaluates the action against the current value, called the dot (.). Text outside actions is emitted unchanged; {{.}} prints the supplied value like fmt.Sprintf("%v", value). section 11.1.2 section 11.6

Render a habit count

Put <p>You have {{.}} habits to follow.</p> in index.html, parse it with template.New("index").Parse(indexPage), and execute it with tpl.Execute(w, 5). The browser renders the value 5 in place of the action. section 11.1.2

Template actions can also express:

  • Structure: {{if ...}}, {{else}}, and {{end}} select conditional output. section 11.6
  • Iteration: {{range ...}} walks slices, arrays, maps, or channels. section 11.6
  • Data access: {{.Field}} reads exposed structure fields, while {{with .Date}} narrows the dot context. section 11.6
Listing 11.10 index.html: Outputting a variable
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Learn Go</title>
</head>
<body>
<h1>Habits</h1>
<p>You have {{.}} habits to follow.</p> #1
</body>
</html>

See the complete HTML fragment that places a template action inside ordinary markup. section 11.1.2

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains parsing, execution, dot-based interpolation, field access, iteration, conditionals, and scoped contexts.
Examples
Demonstrates {{.}} in an HTML habits page and executes it with the value 5.
What it assumes
Assumes familiarity with Go values and functions while teaching the dot value and action delimiters from their first use.
What you can do after
Apply it via Go templates to interpolate values and express conditionals, iteration, field access, and scoped output.
How it connects
Connects template actions with Go templates, fmt.Sprintf, dot notation, conditional statements, range iteration, and structure fields.

Also explained in

Compare how 2 books explain template action →

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.