Use Go’s html/template package to generate HTML pages from reusable templates and application data. It builds on text/template but adds context-aware escaping, making it a better fit for HTML responses than formatting strings directly. The separate html package provides string escaping and unescaping, not structured templates. section 9.1 section 9.1.1
A template is mostly ordinary HTML. Actions in double curly brackets insert data or control rendering: {{.Title}} prints a field, while {{range .Comments}} iterates over a collection. In an HTTP handler, parse the template, then execute it with a data value and an http.ResponseWriter. 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
}
The HTTP handler creates a Page, parses its HTML file, and executes the template into the response writer. section 9.1.1
Escaping depends on where a value appears. For example, in <a href="/user?id={{.Id}}">{{.Content}}</a>, html/template applies URL-query escaping to the ID and HTML escaping to the link text. Its security model treats template authors as trusted and substituted user data as untrusted. With text/template, those escapes would need to be added manually. section 9.1.1
As pages grow, combine templates instead of duplicating markup:
- Include a shared subtemplate with {{template "head.html" .}}; the dot passes the current data to it. section 9.1.5
- Define a base layout with required sections and optional blocks, then parse it with each page-specific template. section 9.1.5
- Parse reusable template sets during initialization and select a named template with ExecuteTemplate when handling a request. section 9.1.5
Templates are a practical default for maintainable HTML output, not a requirement for every response: writing directly to a writer can be lighter when templating is unnecessary. section 9.0 section 9.1

