liveBook · Manning

Template function map

As explained in Go in Practice, Second Edition

A template function map is a mapping from names exposed in templates to Go function values.

A template function map connects names available in a Go template to Go function values. Register it with a new template.Template before parsing the template. section 9.1.2

Use the map in this sequence:

  • Create a template.FuncMap, such as mapping the template name dateFormat to the Go function dateFormat. section 9.1.2
  • Pass the map to t.Funcs, then parse the template before using it. section 9.1.2
  • Execute the parsed template with an io.Writer and data containing the values consumed by the function. section 9.1.2

Formatting a date

The template expression {{.Date | dateFormat "Jan 2, 2006"}} sends .Date through dateFormat. The function receives the layout and time.Time value, then returns the formatted string. section 9.1.2

func parseTemplateString(name, tpl string) *template.Template {
     t:= template.New(name)
     t.Funcs(funcMap)
     t = template.Must(t.Parse(tpl))
     return t
}

A helper can centralize Funcs registration and parsing when multiple templates share the same function set. section 9.1.2

How Go in Practice, Second Edition covers it

How deep it goes
Explains mapping, registration, parsing, execution, and pipeline argument order without covering broader function-set design.
Examples
Uses dateFormat with a Jan 2, 2006 layout to render a time.Time value in HTML.
What you can do after
Apply it via html/template to register custom functions and render formatted values.
How it connects
Connects Go templates with template.Template, template.FuncMap, pipelines, io.Writer, and time.Time.

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.