liveBook · Manning

Template action

As explained in Go in Practice, Second Edition

A Go action is a command or data expression enclosed in double curly brackets within a Go template.

A template action is a Go command or data expression enclosed in double curly brackets, such as {{.Title}}. Actions insert values into templates and can also perform logic, iteration, formatting, and other operations. section 9.1.1 section 9.1.2

Actions can connect operations into pipelines with |. Each operation receives the previous result as its final argument, allowing expressions such as {{.Date | dateFormat "Jan 2, 2006"}}. section 9.1.2

Common template-action uses include:

  • Render struct fields, as with {{.Title}} and {{.Content}}. section 9.1.1
  • Iterate over data with range and end, producing repeated HTML for each comment. section 9.1.1
  • Format values through built-in or custom functions, such as dateFormat. section 9.1.2
  • Escape inserted data according to its HTML context when using html/template. section 9.1.1

Formatting a date through an action pipeline

Register a Go function through template.FuncMap and t.Funcs(funcMap), then use {{.Date | dateFormat "Jan 2, 2006"}} in the template. The date value flows into dateFormat before reaching the output. section 9.1.2

Listing 9.1 A simple HTML template
<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>{{.Title}}</title>     #1
  </head>
  <body>
     <h1>{{.Title}}</h1>       #2
     <p>{{.Content}}</p>       #2
  </body>
</html>

A complete HTML template shows actions embedded alongside ordinary markup, including field rendering in the title, heading, and paragraph. section 9.1.1

How Go in Practice, Second Edition covers it

How deep it goes
Explains field actions, range iteration, pipelines, custom functions, and context-aware escaping without detailing the complete action language.
Examples
Demonstrates title and content fields, comment iteration, URL escaping, HTML escaping, and custom date formatting.
What you can do after
Build HTML templates that render data, iterate collections, apply pipelines, and call registered Go formatting functions.
How it connects
Connects Go templates with html/template, text/template, pipelines, template functions, HTML escaping, and HTTP handlers.

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 Go in Practice, Second Edition. The section links point to the parts of the book it draws on.