Level: IntermediateGo Lang

Go HTML Templates: Render Safe Web Pages Easily

8 min read
Go HTML Templates featured image: fill the blanks, range and branch, and share a layout

Go HTML templates let you build web pages from data, and they escape dangerous characters for you. In this post, you will learn the template syntax and how loops and conditions work. You will also see how to share one layout across pages. Then we will serve a real page with the standard library only.

This lesson builds on Go structs explained and Go maps with examples, because templates read fields and keys from them. We also use ideas from Go HTTP server basics and Go rate limiting with the token bucket. So you may want to skim those first, because the examples build on them.

What Are Go HTML Templates?

In short, a template is a text file with holes in it. The holes are marked with double curly braces, such as {{.Title}}. When you run the template with some data, Go fills the holes. Then it writes the finished page.

Think of a printed invitation with blank spaces for the guest name and the date. You do not design a new card for each guest. Instead, you print the same card and fill in the blanks. Similarly, Go HTML templates fill the blanks of one page with different data.

The package for web pages is html/template. It has the same syntax as text/template, but it adds one big feature. It knows where each value lands in the HTML, so it escapes the value correctly. As a result, it blocks a whole class of attacks. For example, a value inside an attribute is escaped differently from a value inside a script tag.

Why Go HTML Templates Matter

You could build pages by joining strings, but that quickly gets messy and unsafe. For instance, one forgotten escape can open a security hole. So here is what Go HTML templates give you.

  • Safety by default: values are escaped for HTML, attributes, URLs and JavaScript.
  • Clean separation: the design lives in a file, and the logic lives in Go.
  • Reuse: one layout can serve every page on the site.
  • No extra tools: the package is part of the standard library.
  • Easy testing: you can render a template into a buffer and check the text.

Because of this, Go HTML templates are a solid choice for admin pages, emails and small sites. However, large single-page apps usually use a JavaScript framework instead and serve JSON from Go.

How Go HTML Templates Work

With Go HTML templates, you first write a template string or file. Next, you parse it with template.New(...).Parse(...) or template.ParseFS(...). Then you call Execute with a writer and your data. Finally, Go walks through the template, fills each action and writes the HTML.

Go HTML Templates diagram showing a template and data going into Execute and safe HTML coming out
A template with placeholders and a Go data value go into Execute. The output is a finished HTML page with all values escaped.

However, parsing happens once, while execution happens on every request. So parse your templates at start-up, and then reuse them. As a result, each request only pays for the fill-in step, which is very fast.

Template Actions You Will Use Daily

Actions are the parts inside {{ }}, so the table below lists the most common ones.

ActionWhat it doesExample
{{.Name}}Prints a field or map key{{.Title}}
{{if .Free}}...{{else}}...{{end}}Shows text on a conditionFree or price
{{range .Items}}...{{end}}Loops over a slice or mapA list of courses
{{range ...}}...{{else}}Runs when the list is empty“No courses yet”
{{upper .Title}}Calls a custom function on a valueUpper case title
{{define "x"}} and {{block "x" .}}Builds reusable piecesLayouts

Inside range, the dot changes to the current item. Therefore, {{.Title}} in a loop means the title of the current course. Also, a dash such as {{- trims the white space before the action, which keeps the output tidy.

Automatic Escaping

Suppose a user’s name contains <script>. With string joining, that script would run in other visitors’ browsers. With Go HTML templates, however, the angle brackets turn into harmless text. This protection is called contextual escaping. In fact, it is the main reason to use html/template.

Go HTML Templates vs text/template

Go has two template packages with almost the same syntax, so the table below shows the difference.

Featurehtml/templatetext/template
Escapes outputYes, by contextNo
Best forWeb pages and emailsConfig files, code generation
Safe against script injectionYesNo
SyntaxSameSame
Import pathhtml/templatetext/template
Go HTML Templates diagram comparing html/template with text/template
The html/template package turns dangerous characters into safe text, while text/template prints them exactly as they are.

So when should you use which? Use html/template for anything a browser will show, even a small email. On the other hand, use text/template for plain text such as config files.

Go HTML Templates Hands-On: A Course Page

Now let’s build two examples. The first renders a list from a Go slice. The second shares a layout between pages using embed. Also, every output below comes from a real run on Go 1.24.

Step 1: Render a List with Conditions

First, here is the data type and the template. The template shows a price, or the word “Free”. Also, it uses a custom function to make titles upper case.

type Course struct {
	Title string
	Price float64
	Free  bool
}

const page = `<h1>{{.Heading}}</h1>
<ul>
{{- range .Courses}}
  <li>{{.Title | upper}}: {{if .Free}}Free{{else}}${{printf "%.2f" .Price}}{{end}}</li>
{{- else}}
  <li>No courses yet</li>
{{- end}}
</ul>
<p>{{.Note}}</p>
`

Next, the program parses the template with a function map and executes it twice. The second call uses an empty list, so we can see the else branch.

func main() {
	funcs := template.FuncMap{"upper": strings.ToUpper}
	t := template.Must(template.New("page").Funcs(funcs).Parse(page))

	data := map[string]any{
		"Heading": "Go Courses",
		"Courses": []Course{
			{"Go Basics", 0, true},
			{"Go APIs", 29.5, false},
		},
		"Note": `<script>alert("hacked")</script>`,
	}
	if err := t.Execute(os.Stdout, data); err != nil {
		panic(err)
	}

	empty := map[string]any{"Heading": "Empty", "Courses": []Course{}, "Note": "ok"}
	t.Execute(os.Stdout, empty)
}

Now look at the real output. The note field held a script tag. However, it came out as plain, harmless text.

<h1>Go Courses</h1>
<ul>
  <li>GO BASICS: Free</li>
  <li>GO APIS: $29.50</li>
</ul>
<p>&lt;script&gt;alert(&#34;hacked&#34;)&lt;/script&gt;</p>
<h1>Empty</h1>
<ul>
  <li>No courses yet</li>
</ul>
<p>ok</p>

Let’s check the results. First, the free course prints “Free”, and the paid course prints $29.50. Also, the empty list triggers the else branch. Finally, the browser would show the script as text instead of running it.

Step 2: Share a Layout with block and define

Real sites repeat the same header and footer on every page. So we write a base layout with block placeholders, and each page fills them in. Here is templates/base.html, with a simple menu line.

{{define "base"}}<!doctype html>
<html>
<head><title>{{block "title" .}}My Site{{end}}</title></head>
<body>
<p>Home | Courses</p>
{{block "content" .}}Default content{{end}}
</body>
</html>{{end}}

Then templates/courses.html only defines the parts that change.

{{define "title"}}Courses{{end}}
{{define "content"}}<h1>{{.Heading}}</h1>
<p>{{len .Items}} courses available.</p>{{end}}

Step 3: Embed the Files and Serve the Page

Finally, //go:embed packs the template files into the binary. As a result, you can deploy a single file with no folders to copy.

//go:embed templates/*.html
var files embed.FS

var tmpl = template.Must(template.ParseFS(files, "templates/base.html", "templates/courses.html"))

func coursesPage(w http.ResponseWriter, r *http.Request) {
	data := map[string]any{"Heading": "Go Courses", "Items": []string{"Basics", "APIs", "Testing"}}
	if err := tmpl.ExecuteTemplate(w, "base", data); err != nil {
		http.Error(w, "render error", http.StatusInternalServerError)
	}
}

Calling the handler gives this real page.

<!doctype html>
<html>
<head><title>Courses</title></head>
<body>
<p>Home | Courses</p>
<h1>Go Courses</h1>
<p>3 courses available.</p>
</body>
</html>

The title and the content both came from courses.html, while the menu line came from the base layout. Because of this, adding a new page means writing only the small parts that differ. For example, an “About” page would define its own title and content blocks. It would also reuse the same menu line. Likewise, a change to the layout updates every page at once. In addition, designers can edit the HTML files without touching any Go code at all. This is the biggest time saver in Go HTML templates.

Common Mistakes with Go HTML Templates

  • **Using text/template for web pages**: nothing is escaped, so attackers can inject scripts. So always import html/template for HTML.
  • Parsing on every request: this wastes time. Instead, parse once at start-up.
  • **Bypassing escaping with template.HTML**: this tells Go to trust the string. Therefore, use it only for content you wrote yourself.
  • **Ignoring the error from Execute**: the page may be half written. So check the error and log it.
  • **Forgetting the dot after block**: {{block "content" .}} passes data down. Without the dot, the child template sees nothing.

Best Practices for Go HTML Templates

  • Parse templates once, because parsing is the slow part. A package-level template.Must call does this at start-up.
  • **Use embed**, since a single binary is easier to deploy.
  • Keep logic out of templates, so the Go code stays easy to test.
  • Render into a buffer first, which lets you return a clean 500 if rendering fails.
  • Build small custom functions, such as date formatting, with FuncMap.
  • **Set the Content-Type header**, because browsers need to know the page is HTML.

Practice Task

To practise Go HTML templates, build a page that lists blog posts. Each post has a title, an author and a list of tags. Use range for the posts and a second range for the tags. Then add a function that formats a date.

Hint: pass the data as a slice of structs. After that, add FuncMap{"date": func(t time.Time) string {...}} and call it with {{.Published | date}}. Finally, try a title that contains <b> to see the escaping. Then check the page source in your browser to confirm that the tag shows as text.

Official Resources

These pages explain the template syntax and the embed feature in detail.

Quick Recap

  • Go HTML templates fill placeholders in a page with data.
  • Use html/template for web pages, because it escapes values by context.
  • Actions such as if, range and pipelines control what gets printed.
  • define and block let many pages share one layout.
  • Parse once at start-up, then call Execute on each request.
  • Use embed to ship templates inside the binary.

What’s Next?

By now, you can render safe pages. Next, we will look inside the Go runtime and learn how memory and the garbage collector work.

Next up: Go memory and the garbage collector