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
