Go Reference ยท Encoding and Data Formats
The Go html/template package
Reference for Go's html/template package: contextual auto-escaping, template.HTML and other safe types, funcs, nested templates, ExecuteTemplate and errors.
html/template has the same template language as text/template (actions in {{ }}, pipelines, range, if, with, define), but it understands HTML. As it executes, it escapes every value for the exact place where it appears: HTML text, an attribute, a URL, a JavaScript string or a CSS value. That prevents most cross-site scripting (XSS) bugs without you remembering to escape anything.
Use html/template whenever the output is shown in a browser. Use text/template for everything else (e-mails in plain text, config files, code generation), because it never escapes.
t := template.Must(template.New("hi").Parse("<p>{{.}}</p>\n")) t.Execute(os.Stdout, "<b>x</b>") // <p><b>x</b></p>
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func New(name string) *Template func Must(t *Template, err error) *Template func ParseFiles(filenames ...string) (*Template, error) func ParseGlob(pattern string) (*Template, error) func ParseFS(fsys fs.FS, patterns ...string) (*Template, error) func (t *Template) Parse(text string) (*Template, error) func (t *Template) Funcs(funcMap FuncMap) *Template func (t *Template) Option(opt ...string) *Template func (t *Template) Delims(left, right string) *Template func (t *Template) Execute(wr io.Writer, data any) error func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error func (t *Template) Lookup(name string) *Template func (t *Template) Clone() (*Template, error) type HTML string; type HTMLAttr string; type JS string; type CSS string; type URL string; type JSStr string; type Srcset string func HTMLEscapeString(s string) string func JSEscapeString(s string) string
| Name | Description |
|---|---|
name |
Template name. Files get the base name of the file. |
data |
The value available as . in the template: a struct, map, slice or any other value. |
FuncMap |
map[string]any of functions callable from templates. Each must return one value, or a value and an error. |
Option("missingkey=error") |
Fail on a missing map key instead of printing <no value>. |
Errors and edge cases:
- Escaping is decided on the first
Execute; after that,Parseon the same template returns an error. Parse everything first. - A template that cannot be escaped safely (for example an action inside a JavaScript regular expression, or a branch that ends in a different context than it started) fails at
Executetime with anErrorCode-based error. - Writing output to
wrcan fail halfway, and part of the page may already be sent. Render into abytes.Bufferfirst when you need an all-or-nothing response. - Calling a missing template name returns an error from
ExecuteTemplate.
Usage notes
- Never convert untrusted input to
template.HTML,template.JSortemplate.URL. These types tell the package "I vouch for this". Marking user text astemplate.HTMLswitches off protection. - Values in
hrefandsrc: unsafe schemes such asjavascript:are replaced by#ZgotmplZ. If you see that text in your output, the package refused a value it considered dangerous. Fix the data or usetemplate.URLonly for values you built yourself. - Comments: HTML comments in the template text are removed from the output; Go template comments are
{{/* ... */}}. - Layouts: parse a base template with
{{block "content" .}}and clone it per page, or useParseFiles("layout.html", "page.html"). CallingExecuteTemplate(w, "layout.html", data)renders the layout. - Parse once, execute many times. Parsing is slow; a parsed
*Templateis safe for concurrentExecutecalls. Parse at start-up, not per request. - Embedding: combine
ParseFSwith//go:embedto ship templates inside the binary. - Not a sanitizer. It escapes text; it does not remove tags from user-supplied HTML. If you must allow some markup, run it through an HTML sanitizer first.