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
