liveBook · Manning

Execute

As explained in Learn Go with Pocket-Sized Projects

Execute is a Go template API method that evaluates a parsed template against supplied data and writes the rendered result.

Execute renders a parsed Go template using one data value and writes the result to a destination. In an HTTP handler, that destination can be an http.ResponseWriter. Parse the template first, then check the error returned by Execute. section 11.1.2

Render a single value

Parse an embedded page with `tpl, err := template.New("index").Parse(indexPage)`. After checking `err`, call `err = tpl.Execute(w, 5)` and check it again. The template action `{{.}}` receives `5` as its value; other template content is rendered around it. section 11.1.2

Execute accepts one data value. To expose several values, pass a map: `tpl.Execute(w, map[string]interface{}{"Habits": habits, "Date": week})`. The map becomes the template’s dot, so actions can access `{{.Habits}}` and `{{.Date.Start}}`. Inside `{{with .Date}}`, the dot becomes the date value and `{{.Start}}` suffices; a `range` over habits must now start from `.Habits`. section 11.5.1

Choose `html/template` when rendering HTML: it escapes HTML-sensitive input. `text/template` has the same interface for output that does not need that protection. When several template definitions are loaded, use ExecuteTemplate and name the root template rather than relying on Execute. section 11.1.2 section 11.6

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Works through scalar and map data, dot access, and error checks without detailing the rendering engine’s internals.
Examples
Shows an embedded page rendered with `5`, then habits and week dates passed together in a map.
What it assumes
Assumes Go HTTP handler and value syntax while introducing template actions and dot access.
What you can do after
Apply it via Go’s html/template to render scalar or map data into an HTTP response and check execution errors.
How it connects
Connects Execute to template actions, dot, with, range, html/template, 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.