html/template

html/template contextual auto-escaping compared with text/template, the trusted-source security model, trusted types, missingkey, and partial output after Execute errors, checked on Go 1.24.0.

モジュールページの本文は現在英語です。

The html/template package implements data-driven templates for HTML output. It shares the template language with text/template, but it adds contextual auto-escaping so that actions can appear in HTML, attribute, JavaScript, CSS, and URI contexts. Use this package instead of text/template when the output is HTML. The two packages have separate pages and distinct import paths.

Official documentation states the security model clearly: template authors are trusted, while the data argument to Execute is not. Trust the template source; do not treat untrusted strings as template text to parse. Types such as template.HTML, template.JS, and template.URL insert content verbatim. Official docs call that a security risk unless the content comes from a trusted source. They are not recommended here as a shortcut for untrusted data.

Examples were run against Go 1.24.0. They write to bytes.Buffer and print the result with %q. This is not a served HTML page, and nothing in the output is executed in a browser.

Examples were checked against Go 1.24.0. See the official package documentation for the complete API.

Go reference overview →

API index

APISummary
html/template.Execute versus text/template.Executehtml/template escapes untrusted data for HTML context. text/template does not. Both programs print quoted strings, not a live page.
Execute errors, missingkey, and template.HTMLA failed Execute can still leave bytes in the writer. template.HTML is a trusted-type bypass, not a shortcut for untrusted markup.

Contextual auto-escaping versus text/template

When the same template body and the same data string are executed, text/template inserts the data unchanged, while html/template escapes it for an HTML text context. In this example the data is the literal <b>ok</b>. The text/template result still contains angle brackets; the html/template result uses character references.

The escaping is added at parse time according to context. This page demonstrates a plain HTML text context only. It does not claim to have enumerated every JavaScript, CSS, or URL context.

html/template.Execute versus text/template.Execute

func New(name string) *Template
func (t *Template) Parse(text string) (*Template, error)
func (t *Template) Execute(wr io.Writer, data any) error

html/template escapes untrusted data for HTML context. text/template does not. Both programs print quoted strings, not a live page.

ParameterDescription
name, textNew allocates a template. Parse reads the template source, which must be trusted.
wr, dataExecute writes the result to wr. data is treated as untrusted content in html/template.

Returns: Parse returns the template and an error. Execute returns an error if execution or writing fails.

Errors

  • error — A parse or execution error is returned to the caller. This example checks both and then prints the buffers.
  • The two outputs are printed with %q so the escaped and raw forms stay visible as data.
go
package main

import (
	"bytes"
	"fmt"
	htmltemplate "html/template"
	texttemplate "text/template"
)

func main() {
	data := "<b>ok</b>"
	textT, err := texttemplate.New("t").Parse("Hello, {{.}}!")
	if err != nil {
		fmt.Println(err)
		return
	}
	htmlT, err := htmltemplate.New("t").Parse("Hello, {{.}}!")
	if err != nil {
		fmt.Println(err)
		return
	}
	var textOut, htmlOut bytes.Buffer
	if err := textT.Execute(&textOut, data); err != nil {
		fmt.Println("text", err)
	}
	if err := htmlT.Execute(&htmlOut, data); err != nil {
		fmt.Println("html", err)
	}
	fmt.Printf("%q\n", textOut.String())
	fmt.Printf("%q\n", htmlOut.String())
}

Expected output

"Hello, <b>ok</b>!"
"Hello, &lt;b&gt;ok&lt;/b&gt;!"

Related: text/template, html.EscapeString

Official documentation →

Partial Execute output and trusted types

If Execute fails, official documentation says execution stops, but partial results may already have been written to the writer. The first program uses the shared Option missingkey=error: after writing "start yes mid ", lookup of a missing map key stops execution, and the trailing " end" is not written. The buffer still contains the prefix.

Passing template.HTML("<b>ok</b>") inserts the markup verbatim, while a plain string is escaped. Official documentation says use of that type presents a security risk and the content should come from a trusted source. This page shows the difference so the bypass is visible; it is not recommended as a shortcut for untrusted data.

Execute errors, missingkey, and template.HTML

func (t *Template) Option(opt ...string) *Template
func (t *Template) Execute(wr io.Writer, data any) error
type HTML string

A failed Execute can still leave bytes in the writer. template.HTML is a trusted-type bypass, not a shortcut for untrusted markup.

ParameterDescription
optOption strings such as missingkey=error. Unrecognized options panic. missingkey is documented on text/template.Option and applies here too.
wr, dataExecute writes to wr. On error, wr may already contain a prefix of the output.

Returns: Execute returns a non-nil error when execution stops early. The buffer contents are still meaningful and must be discarded if the error matters.

Errors

  • error — missingkey=error reports that the map has no entry for the key, after any earlier output has been written.
  • Do not serve a buffer after a failed Execute without checking the error. Do not wrap untrusted strings as template.HTML to skip escaping.
go
package main

import (
	"bytes"
	"fmt"
	"html/template"
)

func main() {
	t, err := template.New("t").Option("missingkey=error").Parse("start {{.ok}} mid {{.missing}} end")
	if err != nil {
		fmt.Println("parse", err)
		return
	}
	var buf bytes.Buffer
	err = t.Execute(&buf, map[string]string{"ok": "yes"})
	fmt.Printf("%q\n", buf.String())
	fmt.Printf("%v\n", err)

	trusted, err := template.New("u").Parse("X {{.}} Y")
	if err != nil {
		fmt.Println(err)
		return
	}
	var escaped, raw bytes.Buffer
	_ = trusted.Execute(&escaped, "<b>ok</b>")
	_ = trusted.Execute(&raw, template.HTML("<b>ok</b>"))
	fmt.Printf("%q\n", escaped.String())
	fmt.Printf("%q\n", raw.String())
}

Expected output

"start yes mid "
template: t:1:20: executing "t" at <.missing>: map has no entry for key "missing"
"X &lt;b&gt;ok&lt;/b&gt; Y"
"X <b>ok</b> Y"

Related: text/template Option missingkey, Official template.HTML

Official documentation →