liveBook · Manning

Template.Template

As explained in Go in Practice, Second Edition

template.Template is the Go type representing a parsed template together with its associated definitions and execution behavior.

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:

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

How Go in Practice, Second Edition covers it

How deep it goes
Explains creation, function registration, parsing, and execution, without descending into template-engine internals.
Examples
Uses a dateFormat function, an HTML date page, an HTTP handler, and a reusable parsing helper.
What you can do after
Operate/configure template.Template instances for custom-function rendering and reusable template construction.
How it connects
Connects template.Template with template.FuncMap, Parse, Execute, pipelines, and time.Time formatting.

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.