liveBook · Manning

Custom template function

As explained in Go in Practice, Second Edition

A custom template function is an application-defined function registered with a template engine and callable from template actions.

A custom template function is an application-defined Go function registered with a template engine and callable from template actions. It extends the limited built-in command set with application-specific behavior such as date formatting. section 9.1.2

Register a custom function before parsing and executing the template:

  • Map the template-visible name to a Go function in a template.FuncMap. section 9.1.2
  • Pass the map to a new template with Funcs, then parse the template. section 9.1.2
  • Execute the parsed template with input data and an io.Writer. section 9.1.2
  • Account for pipeline argument order: piped output becomes the function's last argument. section 9.1.2

Formatting a date in an HTML template

Use a template action such as {{.Date | dateFormat "Jan 2, 2006"}} with a mapping like template.FuncMap{"dateFormat": dateFormat}. Define dateFormat(layout string, d time.Time) string to return d.Format(layout), register the map before Parse, and execute with a struct containing Date. section 9.1.2

Listing 9.5 Adding template functions
package main

import (
     "html/template"
     "net/http"
     "time"
)
var tpl = `<!DOCTYPE HTML>     #1
<html>
  <head>
    <meta charset="utf-8">
    <title>Date Example</title>
  </head>
  <body>
       <p>{{.Date | dateFormat "Jan 2, 2006"}}</p>     #2
  </body>
</html>`
var funcMap = template.FuncMap{     #3
     "dateFormat": dateFormat,      #3
}                                   #3
func dateFormat(layout string, d time.Time) string {     #4
     return d.Format(layout)                             #4
}                                                        #4
func serveTemplate(res http.ResponseWriter, req *http.Request) {
     t := template.New("date")                       #5
     t.Funcs(funcMap)                    #6
     t.Parse(tpl)                                 #7
     data := struct{ Date time.Time }{       #8
            Date: time.Now(),               
     }                                       #8
     t.Execute(res, data)   #9
} #8
func main() { #8
     http.HandleFunc("/", serveTemplate)   #10
     http.ListenAndServe(":8080", nil)     #8
} #8

The complete listing ties together the template action, function map, dateFormat implementation, registration, parsing, input data, and execution. section 9.1.2

How Go in Practice, Second Edition covers it

How deep it goes
Explains registration, pipeline argument order, parsing, and execution, but does not develop function libraries or error-handling strategies.
Examples
Demonstrates dateFormat with time.Time, the Jan 2, 2006 layout, a FuncMap, and an HTML template action.
What it assumes
Assumes familiarity with Go functions, templates, template actions, and time.Time while clarifying the registration sequence.
What you can do after
Build it from scratch by registering a Go function, parsing a template, and executing it with rendering data.
How it connects
Connects custom functions with template pipelines, template parsing, html/template, text/template, and template execution.

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.