liveBook · Manning

Define action

As explained in Learn Go with Pocket-Sized Projects

A define action is a Go template action that declares a named template body terminated by an end action.

A define action declares a named Go template body with {{ define "name" }} ... {{ end }}. It extracts reusable rendering logic, such as turning a habit into an HTML list item. section 11.5.3

Extract a habit item

Declare the fragment in habititem.html, then invoke it inside the page template: {{- define "habitItem"}} <li class="habit {{ statusCSSClass . }}"> <b>{{.Name}}</b> <span>{{- progress . }}</span> </li> {{- end }} {{- range .Habits }} {{- template "habitItem" . }} {{- end }} The dot passes the current habit into the named template. section 11.5.3

When definitions are split across files, load the template directory with ParseFS and explicitly execute the intended root using ExecuteTemplate. Whitespace-trimming markers affect generated source formatting, so preserve indentation deliberately. section 11.5.3

Listing 11.45 habititem.html: Declaring a template in another file
{{- define "habitItem"}} 
        <li class="habit {{ statusCSSClass . }}"> 
            <b>{{.Name}}</b>
            <span class="{{ if ge .Ticks .WeeklyFrequency -}} done 
➥{{- end -}} "> {{- progress . }}</span>
            <a href="/tick/{{ .ID }}">Tick!</a>
        </li>
{{- end }} 

Inspect the complete habitItem.html declaration, including conditional status markup, progress rendering, links, indentation, and whitespace controls. section 11.5.3

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains declaration syntax, whitespace trimming, multi-file parsing, invocation, and explicit execution selection.
Examples
Uses a habit-item HTML fragment, a habits range, embedded template files, and a named root execution.
What it assumes
Assumes familiarity with Go templates, range loops, template loading, and data access through the dot.
What you can do after
Build it from scratch: extract reusable HTML fragments, invoke them with template, and execute the intended named root.
How it connects
Connects named templates with range, template invocation, ParseFS, embedded files, and ExecuteTemplate.

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.