liveBook · Manning

Html/template package

As explained in Go in Practice, Second Edition

The Go html/template package generates HTML safely from templates containing data substitutions and control logic.

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

How Go in Practice, Second Edition covers it

How deep it goes
Works through field substitution, contextual escaping, iteration, and template composition, then sketches more complex reuse patterns.
Examples
Uses an HTTP page handler, a comments iterator, shared head markup, and a base layout with overridable blocks.
What it assumes
Assumes basic Go structs and HTTP handlers while introducing template actions and context-aware escaping through examples.
What you can do after
Build it from scratch with html/template to render data into HTTP pages and reuse markup across templates.
How it connects
Connects text/template, HTML escaping, HTTP handlers, template inheritance, and cross-site scripting prevention.

Also explained in

Compare how 2 books explain html/template package →

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.