template.Template represents a parsed Go template with its associated definitions and execution behavior. Configure custom functions before parsing, then execute the parsed instance with data and an output writer. section 9.1.2
A practical setup sequence is:
- Create a template with template.New. section 9.1.2
- Register Go functions through template.FuncMap and Funcs. section 9.1.2
- Parse the template before using it. section 9.1.2
- Pass data and an io.Writer to Execute. 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
A complete HTTP-oriented example registers dateFormat, parses an HTML template, and renders a time.Time value through a pipeline. 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 reusable helper centralizes template creation, function registration, parsing, and parse-error handling with template.Must. section 9.1.2
