liveBook · Manning

Template

As explained in Go in Practice, Second Edition

An HTML template is a document template containing markup, data substitutions, and control logic for generating output.

A template generates output from fixed text, data substitutions, and actions. For HTTP pages, Go’s html/template replaces strings written directly to a ResponseWriter with structured HTML that is easier to maintain. Use text/template for plain-text output such as email. section 9.0 section 9.2

In an HTML file, {{.Title}} prints a field from the data passed to Execute. An action can also control output: {{range .Comments}} repeats markup for each comment, and {{end}} closes the range. Inside the range, fields such as {{.Text}} refer to the current comment. section 9.1.1

Listing 9.2 Using a simple HTML template
package main

import (
     "html/template"      #1
     "net/http"
)

type Page struct {
     Title, Content string
}
func displayPage(w http.ResponseWriter, r *http.Request) {
     p := &Page{                                            #2
            Title:   "An Example",                          #2
            Content: "Have fun stormin' da castle.",        #2
     }                                                      #2
     t := template.Must(template.ParseFiles("templates
     /simple.html"))                #3
     t.Execute(w, p)                                     #4
}
func main() {
     http.HandleFunc("/", displayPage)      #5
     http.ListenAndServe(":8080", nil)      #5
}

A complete HTTP handler parses an HTML file, constructs page data, and executes the template into the response. section 9.1.1

Choose html/template when rendering HTML with untrusted data. It escapes inserted values according to their context: a value in a URL query and one in visible page text need different treatment. The security model trusts the template but not data supplied through its variables; text/template does not add that HTML-aware escaping. section 9.1.1 section 9.2

Keep data generation in application code and display formatting in the template. For formatting not provided by built-in functions, register a function with template.FuncMap before parsing. A date-formatting function can then be used as {{.Date | dateFormat "Jan 2, 2006"}}. Parsing at a suitable point outside repeated rendering can also reduce processing work. section 9.1.2 section 9.0

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 date example connects the template pipeline to a Go function registered through FuncMap. section 9.1.2

For plain-text email, execute a text/template into a buffer, then send the resulting content through a mail client. Injected values are not automatically HTML-escaped; use escaping functions if the output requires them. HTML email can instead use html/template. section 9.2

How Go in Practice, Second Edition covers it

How deep it goes
Works through field substitution, iteration, context-aware escaping, custom functions, and email rendering with Go implementations.
Examples
Uses an HTML page with comments, a date-formatting function, and a templated email message.
What it assumes
Assumes basic Go structs and HTTP handlers while introducing template actions and execution through examples.
What you can do after
Build it from scratch using Go templates to render HTML pages or email, with iteration and custom display functions.
How it connects
Connects templates to HTTP handlers, cross-site scripting prevention, function pipelines, and plain-text email.

Also explained in

Compare how 21 books explain template →

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.