version: 1.10

package template

import "html/template"

Overview

Package template (html/template) implements data-driven templates for generating
HTML output safe against code injection. It provides the same interface as
package text/template and should be used instead of text/template whenever the
output is HTML.

The documentation here focuses on the security features of the package. For
information about how to program the templates themselves, see the documentation
for text/template.

Introduction

This package wraps package text/template so you can share its template API to
parse and execute HTML templates safely.

  1. tmpl, err := template.New("name").Parse(...)
  2. // Error checking elided
  3. err = tmpl.Execute(out, data)

If successful, tmpl will now be injection-safe. Otherwise, err is an error
defined in the docs for ErrorCode.

HTML templates treat data values as plain text which should be encoded so they
can be safely embedded in an HTML document. The escaping is contextual, so
actions can appear within JavaScript, CSS, and URI contexts.

The security model used by this package assumes that template authors are
trusted, while Execute’s data parameter is not. More details are provided below.

Example

  1. import "text/template"
  2. ...
  3. t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
  4. err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>")

produces

  1. Hello, <script>alert('you have been pwned')</script>!

but the contextual autoescaping in html/template

  1. import "html/template"
  2. ...
  3. t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
  4. err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>")

produces safe, escaped HTML output

  1. Hello, &lt;script&gt;alert(&#39;you have been pwned&#39;)&lt;/script&gt;!

Contexts

This package understands HTML, CSS, JavaScript, and URIs. It adds sanitizing
functions to each simple action pipeline, so given the excerpt

  1. <a href="/search?q={{.}}">{{.}}</a>

At parse time each {{.}} is overwritten to add escaping functions as necessary.
In this case it becomes

  1. <a href="/search?q={{. | urlescaper | attrescaper}}">{{. | htmlescaper}}</a>

where urlescaper, attrescaper, and htmlescaper are aliases for internal escaping
functions.

Errors

See the documentation of ErrorCode for details.

A fuller picture

The rest of this package comment may be skipped on first reading; it includes
details necessary to understand escaping contexts and error messages. Most users
will not need to understand these details.

Contexts

Assuming {{.}} is O'Reilly: How are <i>you</i>?, the table below shows how
{{.}} appears when used in the context to the left.

  1. Context {{.}} After
  2. {{.}} O'Reilly: How are &lt;i&gt;you&lt;/i&gt;?
  3. <a title='{{.}}'> O&#39;Reilly: How are you?
  4. <a href="/{{.}}"> O&#39;Reilly: How are %3ci%3eyou%3c/i%3e?
  5. <a href="?q={{.}}"> O&#39;Reilly%3a%20How%20are%3ci%3e...%3f
  6. <a onx='f("{{.}}")'> O\x27Reilly: How are \x3ci\x3eyou...?
  7. <a onx='f({{.}})'> "O\x27Reilly: How are \x3ci\x3eyou...?"
  8. <a onx='pattern = /{{.}}/;'> O\x27Reilly: How are \x3ci\x3eyou...\x3f

If used in an unsafe context, then the value might be filtered out:

  1. Context {{.}} After
  2. <a href="{{.}}"> #ZgotmplZ

since “O’Reilly:” is not an allowed protocol like “http:”.

If {{.}} is the innocuous word, left, then it can appear more widely,

  1. Context {{.}} After
  2. {{.}} left
  3. <a title='{{.}}'> left
  4. <a href='{{.}}'> left
  5. <a href='/{{.}}'> left
  6. <a href='?dir={{.}}'> left
  7. <a style="border-{{.}}: 4px"> left
  8. <a style="align: {{.}}"> left
  9. <a style="background: '{{.}}'> left
  10. <a style="background: url('{{.}}')> left
  11. <style>p.{{.}} {color:red}</style> left

Non-string values can be used in JavaScript contexts. If {{.}} is

  1. struct{A,B string}{ "foo", "bar" }

in the escaped template

  1. <script>var pair = {{.}};</script>

then the template output is

  1. <script>var pair = {"A": "foo", "B": "bar"};</script>

See package json to understand how non-string content is marshaled for embedding
in JavaScript contexts.

Typed Strings

By default, this package assumes that all pipelines produce a plain text string.
It adds escaping pipeline stages necessary to correctly and safely embed that
plain text string in the appropriate context.

When a data value is not plain text, you can make sure it is not over-escaped by
marking it with its type.

Types HTML, JS, URL, and others from content.go can carry safe content that is
exempted from escaping.

The template

  1. Hello, {{.}}!

can be invoked with

  1. tmpl.Execute(out, template.HTML(`<b>World</b>`))

to produce

  1. Hello, <b>World</b>!

instead of the

  1. Hello, &lt;b&gt;World&lt;b&gt;!

that would have been produced if {{.}} was a regular string.

Security Model

https://rawgit.com/mikesamuel/sanitized-jquery-templates/trunk/safetemplate.html#problem_definition
defines “safe” as used by this package.

This package assumes that template authors are trusted, that Execute’s data
parameter is not, and seeks to preserve the properties below in the face of
untrusted data:

Structure Preservation Property: “… when a template author writes an HTML tag
in a safe templating language, the browser will interpret the corresponding
portion of the output as a tag regardless of the values of untrusted data, and
similarly for other structures such as attribute boundaries and JS and CSS
string boundaries.”

Code Effect Property: “… only code specified by the template author should run
as a result of injecting the template output into a page and all code specified
by the template author should run as a result of the same.”

Least Surprise Property: “A developer (or code reviewer) familiar with HTML,
CSS, and JavaScript, who knows that contextual autoescaping happens should be
able to look at a {{.}} and correctly infer what sanitization happens.”


Example:

  1. const tpl = `
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="UTF-8">
  6. <title>{{.Title}}</title>
  7. </head>
  8. <body>
  9. {{range .Items}}<div>{{ . }}</div>{{else}}<div><strong>no rows</strong></div>{{end}}
  10. </body>
  11. </html>`
  12. check := func(err error) {
  13. if err != nil {
  14. log.Fatal(err)
  15. }
  16. }
  17. t, err := template.New("webpage").Parse(tpl)
  18. check(err)
  19. data := struct {
  20. Title string
  21. Items []string
  22. }{
  23. Title: "My page",
  24. Items: []string{
  25. "My photos",
  26. "My blog",
  27. },
  28. }
  29. err = t.Execute(os.Stdout, data)
  30. check(err)
  31. noItems := struct {
  32. Title string
  33. Items []string
  34. }{
  35. Title: "My another page",
  36. Items: []string{},
  37. }
  38. err = t.Execute(os.Stdout, noItems)
  39. check(err)
  40. // Output:
  41. // <!DOCTYPE html>
  42. // <html>
  43. // <head>
  44. // <meta charset="UTF-8">
  45. // <title>My page</title>
  46. // </head>
  47. // <body>
  48. // <div>My photos</div><div>My blog</div>
  49. // </body>
  50. // </html>
  51. // <!DOCTYPE html>
  52. // <html>
  53. // <head>
  54. // <meta charset="UTF-8">
  55. // <title>My another page</title>
  56. // </head>
  57. // <body>
  58. // <div><strong>no rows</strong></div>
  59. // </body>
  60. // </html>


Example:

  1. check := func(err error) {
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. }
  6. t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
  7. check(err)
  8. err = t.ExecuteTemplate(os.Stdout, "T", "<script>alert('you have been pwned')</script>")
  9. check(err)
  10. // Output:
  11. // Hello, &lt;script&gt;alert(&#39;you have been pwned&#39;)&lt;/script&gt;!


Example:

  1. const s = `"Fran & Freddie's Diner" <tasty@example.com>`
  2. v := []interface{}{`"Fran & Freddie's Diner"`, ' ', `<tasty@example.com>`}
  3. fmt.Println(template.HTMLEscapeString(s))
  4. template.HTMLEscape(os.Stdout, []byte(s))
  5. fmt.Fprintln(os.Stdout, "")
  6. fmt.Println(template.HTMLEscaper(v...))
  7. fmt.Println(template.JSEscapeString(s))
  8. template.JSEscape(os.Stdout, []byte(s))
  9. fmt.Fprintln(os.Stdout, "")
  10. fmt.Println(template.JSEscaper(v...))
  11. fmt.Println(template.URLQueryEscaper(v...))
  12. // Output:
  13. // &#34;Fran &amp; Freddie&#39;s Diner&#34; &lt;tasty@example.com&gt;
  14. // &#34;Fran &amp; Freddie&#39;s Diner&#34; &lt;tasty@example.com&gt;
  15. // &#34;Fran &amp; Freddie&#39;s Diner&#34;32&lt;tasty@example.com&gt;
  16. // \"Fran & Freddie\'s Diner\" \x3Ctasty@example.com\x3E
  17. // \"Fran & Freddie\'s Diner\" \x3Ctasty@example.com\x3E
  18. // \"Fran & Freddie\'s Diner\"32\x3Ctasty@example.com\x3E
  19. // %22Fran+%26+Freddie%27s+Diner%2232%3Ctasty%40example.com%3E

Index

Examples

Package files

attr.go content.go context.go css.go doc.go error.go escape.go html.go js.go template.go transition.go url.go

func HTMLEscape

  1. func HTMLEscape(w io.Writer, b []byte)

HTMLEscape writes to w the escaped HTML equivalent of the plain text data b.

func HTMLEscapeString

  1. func HTMLEscapeString(s string) string

HTMLEscapeString returns the escaped HTML equivalent of the plain text data s.

func HTMLEscaper

  1. func HTMLEscaper(args ...interface{}) string

HTMLEscaper returns the escaped HTML equivalent of the textual representation of
its arguments.

func IsTrue

  1. func IsTrue(val interface{}) (truth, ok bool)

IsTrue reports whether the value is ‘true’, in the sense of not the zero of its
type, and whether the value has a meaningful truth value. This is the definition
of truth used by if and other such actions.

func JSEscape

  1. func JSEscape(w io.Writer, b []byte)

JSEscape writes to w the escaped JavaScript equivalent of the plain text data b.

func JSEscapeString

  1. func JSEscapeString(s string) string

JSEscapeString returns the escaped JavaScript equivalent of the plain text data
s.

func JSEscaper

  1. func JSEscaper(args ...interface{}) string

JSEscaper returns the escaped JavaScript equivalent of the textual
representation of its arguments.

func URLQueryEscaper

  1. func URLQueryEscaper(args ...interface{}) string

URLQueryEscaper returns the escaped value of the textual representation of its
arguments in a form suitable for embedding in a URL query.

type CSS

  1. type CSS string

CSS encapsulates known safe content that matches any of:

  1. 1. The CSS3 stylesheet production, such as `p { color: purple }`.
  2. 2. The CSS3 rule production, such as `a[href=~"https:"].foo#bar`.
  3. 3. CSS3 declaration productions, such as `color: red; margin: 2px`.
  4. 4. The CSS3 value production, such as `rgba(0, 0, 255, 127)`.

See http://www.w3.org/TR/css3-syntax/#parsing and
https://web.archive.org/web/20090211114933/http://w3.org/TR/css3-syntax#style

Use of this type presents a security risk: the encapsulated content should come
from a trusted source, as it will be included verbatim in the template output.

type Error

  1. type Error struct {
  2. // ErrorCode describes the kind of error.
  3. ErrorCode ErrorCode
  4. // Node is the node that caused the problem, if known.
  5. // If not nil, it overrides Name and Line.
  6. Node parse.Node
  7. // Name is the name of the template in which the error was encountered.
  8. Name string
  9. // Line is the line number of the error in the template source or 0.
  10. Line int
  11. // Description is a human-readable description of the problem.
  12. Description string
  13. }

Error describes a problem encountered during template Escaping.

func (*Error) Error

  1. func (e *Error) Error() string

type ErrorCode

  1. type ErrorCode int

ErrorCode is a code for a kind of error.

  1. const (
  2. // OK indicates the lack of an error.
  3. OK ErrorCode = iota
  4.  
  5. // ErrAmbigContext: "... appears in an ambiguous context within a URL"
  6. // Example:
  7. // <a href="
  8. // {{if .C}}
  9. // /path/
  10. // {{else}}
  11. // /search?q=
  12. // {{end}}
  13. // {{.X}}
  14. // ">
  15. // Discussion:
  16. // {{.X}} is in an ambiguous URL context since, depending on {{.C}},
  17. // it may be either a URL suffix or a query parameter.
  18. // Moving {{.X}} into the condition removes the ambiguity:
  19. // <a href="{{if .C}}/path/{{.X}}{{else}}/search?q={{.X}}">
  20. ErrAmbigContext
  21.  
  22. // ErrBadHTML: "expected space, attr name, or end of tag, but got ...",
  23. // "... in unquoted attr", "... in attribute name"
  24. // Example:
  25. // <a href = /search?q=foo>
  26. // <href=foo>
  27. // <form na<e=...>
  28. // <option selected<
  29. // Discussion:
  30. // This is often due to a typo in an HTML element, but some runes
  31. // are banned in tag names, attribute names, and unquoted attribute
  32. // values because they can tickle parser ambiguities.
  33. // Quoting all attributes is the best policy.
  34. ErrBadHTML
  35.  
  36. // ErrBranchEnd: "{{if}} branches end in different contexts"
  37. // Example:
  38. // {{if .C}}<a href="{{end}}{{.X}}
  39. // Discussion:
  40. // Package html/template statically examines each path through an
  41. // {{if}}, {{range}}, or {{with}} to escape any following pipelines.
  42. // The example is ambiguous since {{.X}} might be an HTML text node,
  43. // or a URL prefix in an HTML attribute. The context of {{.X}} is
  44. // used to figure out how to escape it, but that context depends on
  45. // the run-time value of {{.C}} which is not statically known.
  46. //
  47. // The problem is usually something like missing quotes or angle
  48. // brackets, or can be avoided by refactoring to put the two contexts
  49. // into different branches of an if, range or with. If the problem
  50. // is in a {{range}} over a collection that should never be empty,
  51. // adding a dummy {{else}} can help.
  52. ErrBranchEnd
  53.  
  54. // ErrEndContext: "... ends in a non-text context: ..."
  55. // Examples:
  56. // <div
  57. // <div title="no close quote>
  58. // <script>f()
  59. // Discussion:
  60. // Executed templates should produce a DocumentFragment of HTML.
  61. // Templates that end without closing tags will trigger this error.
  62. // Templates that should not be used in an HTML context or that
  63. // produce incomplete Fragments should not be executed directly.
  64. //
  65. // {{define "main"}} <script>{{template "helper"}}</script> {{end}}
  66. // {{define "helper"}} document.write(' <div title=" ') {{end}}
  67. //
  68. // "helper" does not produce a valid document fragment, so should
  69. // not be Executed directly.
  70. ErrEndContext
  71.  
  72. // ErrNoSuchTemplate: "no such template ..."
  73. // Examples:
  74. // {{define "main"}}<div {{template "attrs"}}>{{end}}
  75. // {{define "attrs"}}href="{{.URL}}"{{end}}
  76. // Discussion:
  77. // Package html/template looks through template calls to compute the
  78. // context.
  79. // Here the {{.URL}} in "attrs" must be treated as a URL when called
  80. // from "main", but you will get this error if "attrs" is not defined
  81. // when "main" is parsed.
  82. ErrNoSuchTemplate
  83.  
  84. // ErrOutputContext: "cannot compute output context for template ..."
  85. // Examples:
  86. // {{define "t"}}{{if .T}}{{template "t" .T}}{{end}}{{.H}}",{{end}}
  87. // Discussion:
  88. // A recursive template does not end in the same context in which it
  89. // starts, and a reliable output context cannot be computed.
  90. // Look for typos in the named template.
  91. // If the template should not be called in the named start context,
  92. // look for calls to that template in unexpected contexts.
  93. // Maybe refactor recursive templates to not be recursive.
  94. ErrOutputContext
  95.  
  96. // ErrPartialCharset: "unfinished JS regexp charset in ..."
  97. // Example:
  98. // <script>var pattern = /foo[{{.Chars}}]/</script>
  99. // Discussion:
  100. // Package html/template does not support interpolation into regular
  101. // expression literal character sets.
  102. ErrPartialCharset
  103.  
  104. // ErrPartialEscape: "unfinished escape sequence in ..."
  105. // Example:
  106. // <script>alert("\{{.X}}")</script>
  107. // Discussion:
  108. // Package html/template does not support actions following a
  109. // backslash.
  110. // This is usually an error and there are better solutions; for
  111. // example
  112. // <script>alert("{{.X}}")</script>
  113. // should work, and if {{.X}} is a partial escape sequence such as
  114. // "xA0", mark the whole sequence as safe content: JSStr(`\xA0`)
  115. ErrPartialEscape
  116.  
  117. // ErrRangeLoopReentry: "on range loop re-entry: ..."
  118. // Example:
  119. // <script>var x = [{{range .}}'{{.}},{{end}}]</script>
  120. // Discussion:
  121. // If an iteration through a range would cause it to end in a
  122. // different context than an earlier pass, there is no single context.
  123. // In the example, there is missing a quote, so it is not clear
  124. // whether {{.}} is meant to be inside a JS string or in a JS value
  125. // context. The second iteration would produce something like
  126. //
  127. // <script>var x = ['firstValue,'secondValue]</script>
  128. ErrRangeLoopReentry
  129.  
  130. // ErrSlashAmbig: '/' could start a division or regexp.
  131. // Example:
  132. // <script>
  133. // {{if .C}}var x = 1{{end}}
  134. // /-{{.N}}/i.test(x) ? doThis : doThat();
  135. // </script>
  136. // Discussion:
  137. // The example above could produce `var x = 1/-2/i.test(s)...`
  138. // in which the first '/' is a mathematical division operator or it
  139. // could produce `/-2/i.test(s)` in which the first '/' starts a
  140. // regexp literal.
  141. // Look for missing semicolons inside branches, and maybe add
  142. // parentheses to make it clear which interpretation you intend.
  143. ErrSlashAmbig
  144.  
  145. // ErrPredefinedEscaper: "predefined escaper ... disallowed in template"
  146. // Example:
  147. // <div class={{. | html}}>Hello<div>
  148. // Discussion:
  149. // Package html/template already contextually escapes all pipelines to
  150. // produce HTML output safe against code injection. Manually escaping
  151. // pipeline output using the predefined escapers "html" or "urlquery" is
  152. // unnecessary, and may affect the correctness or safety of the escaped
  153. // pipeline output in Go 1.8 and earlier.
  154. //
  155. // In most cases, such as the given example, this error can be resolved by
  156. // simply removing the predefined escaper from the pipeline and letting the
  157. // contextual autoescaper handle the escaping of the pipeline. In other
  158. // instances, where the predefined escaper occurs in the middle of a
  159. // pipeline where subsequent commands expect escaped input, e.g.
  160. // {{.X | html | makeALink}}
  161. // where makeALink does
  162. // return `<a href="`+input+`">link</a>`
  163. // consider refactoring the surrounding template to make use of the
  164. // contextual autoescaper, i.e.
  165. // <a href="{{.X}}">link</a>
  166. //
  167. // To ease migration to Go 1.9 and beyond, "html" and "urlquery" will
  168. // continue to be allowed as the last command in a pipeline. However, if the
  169. // pipeline occurs in an unquoted attribute value context, "html" is
  170. // disallowed. Avoid using "html" and "urlquery" entirely in new templates.
  171. ErrPredefinedEscaper
  172. )

We define codes for each error that manifests while escaping templates, but
escaped templates may also fail at runtime.

Output: “ZgotmplZ” Example:

  1. <img src="{{.X}}">
  2. where {{.X}} evaluates to `javascript:...`

Discussion:

  1. "ZgotmplZ" is a special value that indicates that unsafe content reached a
  2. CSS or URL context at runtime. The output of the example will be
  3. <img src="#ZgotmplZ">
  4. If the data comes from a trusted source, use content types to exempt it
  5. from filtering: URL(`javascript:...`).

type FuncMap

  1. type FuncMap map[string]interface{}

FuncMap is the type of the map defining the mapping from names to functions.
Each function must have either a single return value, or two return values of
which the second has type error. In that case, if the second (error) argument
evaluates to non-nil during execution, execution terminates and Execute returns
that error. FuncMap has the same base type as FuncMap in “text/template”, copied
here so clients need not import “text/template”.

type HTML

  1. type HTML string

HTML encapsulates a known safe HTML document fragment. It should not be used for
HTML from a third-party, or HTML with unclosed tags or comments. The outputs of
a sound HTML sanitizer and a template escaped by this package are fine for use
with HTML.

Use of this type presents a security risk: the encapsulated content should come
from a trusted source, as it will be included verbatim in the template output.

type HTMLAttr

  1. type HTMLAttr string

HTMLAttr encapsulates an HTML attribute from a trusted source, for example, dir="ltr".

Use of this type presents a security risk: the encapsulated content should come
from a trusted source, as it will be included verbatim in the template output.

type JS

  1. type JS string

JS encapsulates a known safe EcmaScript5 Expression, for example, (x + y * z()). Template authors are responsible for ensuring that typed expressions do
not break the intended precedence and that there is no statement/expression
ambiguity as when passing an expression like “{ foo: bar() }\n‘foo’“, which
is both a valid Expression and a valid Program with a very different meaning.

Use of this type presents a security risk: the encapsulated content should come
from a trusted source, as it will be included verbatim in the template output.

Using JS to include valid but untrusted JSON is not safe. A safe alternative is
to parse the JSON with json.Unmarshal and then pass the resultant object into
the template, where it will be converted to sanitized JSON when presented in a
JavaScript context.

type JSStr

  1. type JSStr string

JSStr encapsulates a sequence of characters meant to be embedded between quotes
in a JavaScript expression. The string must match a series of StringCharacters:

  1. StringCharacter :: SourceCharacter but not `\` or LineTerminator
  2. | EscapeSequence

Note that LineContinuations are not allowed. JSStr(“foo\nbar”) is fine, but
JSStr(“foo\\nbar”) is not.

Use of this type presents a security risk: the encapsulated content should come
from a trusted source, as it will be included verbatim in the template output.

type Srcset

  1. type Srcset string

Srcset encapsulates a known safe srcset attribute (see
http://w3c.github.io/html/semantics-embedded-content.html#element-attrdef-img-srcset).

Use of this type presents a security risk: the encapsulated content should come
from a trusted source, as it will be included verbatim in the template output.

type Template

  1. type Template struct {
  2.  
  3. // The underlying template's parse tree, updated to be HTML-safe.
  4. Tree *parse.Tree
  5. // contains filtered or unexported fields
  6. }

Template is a specialized Template from “text/template” that produces a safe
HTML document fragment.


Example:

  1. const (
  2. master = `Names:{{block "list" .}}{{"\n"}}{{range .}}{{println "-" .}}{{end}}{{end}}`
  3. overlay = `{{define "list"}} {{join . ", "}}{{end}} `
  4. )
  5. var (
  6. funcs = template.FuncMap{"join": strings.Join}
  7. guardians = []string{"Gamora", "Groot", "Nebula", "Rocket", "Star-Lord"}
  8. )
  9. masterTmpl, err := template.New("master").Funcs(funcs).Parse(master)
  10. if err != nil {
  11. log.Fatal(err)
  12. }
  13. overlayTmpl, err := template.Must(masterTmpl.Clone()).Parse(overlay)
  14. if err != nil {
  15. log.Fatal(err)
  16. }
  17. if err := masterTmpl.Execute(os.Stdout, guardians); err != nil {
  18. log.Fatal(err)
  19. }
  20. if err := overlayTmpl.Execute(os.Stdout, guardians); err != nil {
  21. log.Fatal(err)
  22. }
  23. // Output:
  24. // Names:
  25. // - Gamora
  26. // - Groot
  27. // - Nebula
  28. // - Rocket
  29. // - Star-Lord
  30. // Names: Gamora, Groot, Nebula, Rocket, Star-Lord


Example:

  1. // Here we create a temporary directory and populate it with our sample
  2. // template definition files; usually the template files would already
  3. // exist in some location known to the program.
  4. dir := createTestDir([]templateFile{
  5. // T0.tmpl is a plain template file that just invokes T1.
  6. {"T0.tmpl", `T0 invokes T1: ({{template "T1"}})`},
  7. // T1.tmpl defines a template, T1 that invokes T2.
  8. {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
  9. // T2.tmpl defines a template T2.
  10. {"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},
  11. })
  12. // Clean up after the test; another quirk of running as an example.
  13. defer os.RemoveAll(dir)
  14. // pattern is the glob pattern used to find all the template files.
  15. pattern := filepath.Join(dir, "*.tmpl")
  16. // Here starts the example proper.
  17. // T0.tmpl is the first name matched, so it becomes the starting template,
  18. // the value returned by ParseGlob.
  19. tmpl := template.Must(template.ParseGlob(pattern))
  20. err := tmpl.Execute(os.Stdout, nil)
  21. if err != nil {
  22. log.Fatalf("template execution: %s", err)
  23. }
  24. // Output:
  25. // T0 invokes T1: (T1 invokes T2: (This is T2))


Example:

  1. // Here we create a temporary directory and populate it with our sample
  2. // template definition files; usually the template files would already
  3. // exist in some location known to the program.
  4. dir := createTestDir([]templateFile{
  5. // T1.tmpl defines a template, T1 that invokes T2.
  6. {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
  7. // T2.tmpl defines a template T2.
  8. {"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},
  9. })
  10. // Clean up after the test; another quirk of running as an example.
  11. defer os.RemoveAll(dir)
  12. // pattern is the glob pattern used to find all the template files.
  13. pattern := filepath.Join(dir, "*.tmpl")
  14. // Here starts the example proper.
  15. // Load the helpers.
  16. templates := template.Must(template.ParseGlob(pattern))
  17. // Add one driver template to the bunch; we do this with an explicit template definition.
  18. _, err := templates.Parse("{{define `driver1`}}Driver 1 calls T1: ({{template `T1`}})\n{{end}}")
  19. if err != nil {
  20. log.Fatal("parsing driver1: ", err)
  21. }
  22. // Add another driver template.
  23. _, err = templates.Parse("{{define `driver2`}}Driver 2 calls T2: ({{template `T2`}})\n{{end}}")
  24. if err != nil {
  25. log.Fatal("parsing driver2: ", err)
  26. }
  27. // We load all the templates before execution. This package does not require
  28. // that behavior but html/template's escaping does, so it's a good habit.
  29. err = templates.ExecuteTemplate(os.Stdout, "driver1", nil)
  30. if err != nil {
  31. log.Fatalf("driver1 execution: %s", err)
  32. }
  33. err = templates.ExecuteTemplate(os.Stdout, "driver2", nil)
  34. if err != nil {
  35. log.Fatalf("driver2 execution: %s", err)
  36. }
  37. // Output:
  38. // Driver 1 calls T1: (T1 invokes T2: (This is T2))
  39. // Driver 2 calls T2: (This is T2)


Example:

  1. // Here we create different temporary directories and populate them with our sample
  2. // template definition files; usually the template files would already
  3. // exist in some location known to the program.
  4. dir1 := createTestDir([]templateFile{
  5. // T1.tmpl is a plain template file that just invokes T2.
  6. {"T1.tmpl", `T1 invokes T2: ({{template "T2"}})`},
  7. })
  8. dir2 := createTestDir([]templateFile{
  9. // T2.tmpl defines a template T2.
  10. {"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},
  11. })
  12. // Clean up after the test; another quirk of running as an example.
  13. defer func(dirs ...string) {
  14. for _, dir := range dirs {
  15. os.RemoveAll(dir)
  16. }
  17. }(dir1, dir2)
  18. // Here starts the example proper.
  19. // Let's just parse only dir1/T0 and dir2/T2
  20. paths := []string{
  21. filepath.Join(dir1, "T1.tmpl"),
  22. filepath.Join(dir2, "T2.tmpl"),
  23. }
  24. tmpl := template.Must(template.ParseFiles(paths...))
  25. err := tmpl.Execute(os.Stdout, nil)
  26. if err != nil {
  27. log.Fatalf("template execution: %s", err)
  28. }
  29. // Output:
  30. // T1 invokes T2: (This is T2)


Example:

  1. // Here we create a temporary directory and populate it with our sample
  2. // template definition files; usually the template files would already
  3. // exist in some location known to the program.
  4. dir := createTestDir([]templateFile{
  5. // T0.tmpl is a plain template file that just invokes T1.
  6. {"T0.tmpl", "T0 ({{.}} version) invokes T1: ({{template `T1`}})\n"},
  7. // T1.tmpl defines a template, T1 that invokes T2. Note T2 is not defined
  8. {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
  9. })
  10. // Clean up after the test; another quirk of running as an example.
  11. defer os.RemoveAll(dir)
  12. // pattern is the glob pattern used to find all the template files.
  13. pattern := filepath.Join(dir, "*.tmpl")
  14. // Here starts the example proper.
  15. // Load the drivers.
  16. drivers := template.Must(template.ParseGlob(pattern))
  17. // We must define an implementation of the T2 template. First we clone
  18. // the drivers, then add a definition of T2 to the template name space.
  19. // 1. Clone the helper set to create a new name space from which to run them.
  20. first, err := drivers.Clone()
  21. if err != nil {
  22. log.Fatal("cloning helpers: ", err)
  23. }
  24. // 2. Define T2, version A, and parse it.
  25. _, err = first.Parse("{{define `T2`}}T2, version A{{end}}")
  26. if err != nil {
  27. log.Fatal("parsing T2: ", err)
  28. }
  29. // Now repeat the whole thing, using a different version of T2.
  30. // 1. Clone the drivers.
  31. second, err := drivers.Clone()
  32. if err != nil {
  33. log.Fatal("cloning drivers: ", err)
  34. }
  35. // 2. Define T2, version B, and parse it.
  36. _, err = second.Parse("{{define `T2`}}T2, version B{{end}}")
  37. if err != nil {
  38. log.Fatal("parsing T2: ", err)
  39. }
  40. // Execute the templates in the reverse order to verify the
  41. // first is unaffected by the second.
  42. err = second.ExecuteTemplate(os.Stdout, "T0.tmpl", "second")
  43. if err != nil {
  44. log.Fatalf("second execution: %s", err)
  45. }
  46. err = first.ExecuteTemplate(os.Stdout, "T0.tmpl", "first")
  47. if err != nil {
  48. log.Fatalf("first: execution: %s", err)
  49. }
  50. // Output:
  51. // T0 (second version) invokes T1: (T1 invokes T2: (T2, version B))
  52. // T0 (first version) invokes T1: (T1 invokes T2: (T2, version A))

func Must

  1. func Must(t *Template, err error) *Template

Must is a helper that wraps a call to a function returning (*Template, error)
and panics if the error is non-nil. It is intended for use in variable
initializations such as

  1. var t = template.Must(template.New("name").Parse("html"))

func New

  1. func New(name string) *Template

New allocates a new HTML template with the given name.

func ParseFiles

  1. func ParseFiles(filenames ...string) (*Template, error)

ParseFiles creates a new Template and parses the template definitions from the
named files. The returned template’s name will have the (base) name and (parsed)
contents of the first file. There must be at least one file. If an error occurs,
parsing stops and the returned *Template is nil.

When parsing multiple files with the same name in different directories, the
last one mentioned will be the one that results. For instance,
ParseFiles(“a/foo”, “b/foo”) stores “b/foo” as the template named “foo”, while
“a/foo” is unavailable.

func ParseGlob

  1. func ParseGlob(pattern string) (*Template, error)

ParseGlob creates a new Template and parses the template definitions from the
files identified by the pattern, which must match at least one file. The
returned template will have the (base) name and (parsed) contents of the first
file matched by the pattern. ParseGlob is equivalent to calling ParseFiles with
the list of files matched by the pattern.

When parsing multiple files with the same name in different directories, the
last one mentioned will be the one that results.

func (*Template) AddParseTree

  1. func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error)

AddParseTree creates a new template with the name and parse tree and associates
it with t.

It returns an error if t or any associated template has already been executed.

func (*Template) Clone

  1. func (t *Template) Clone() (*Template, error)

Clone returns a duplicate of the template, including all associated templates.
The actual representation is not copied, but the name space of associated
templates is, so further calls to Parse in the copy will add templates to the
copy but not to the original. Clone can be used to prepare common templates and
use them with variant definitions for other templates by adding the variants
after the clone is made.

It returns an error if t has already been executed.

func (*Template) DefinedTemplates

  1. func (t *Template) DefinedTemplates() string

DefinedTemplates returns a string listing the defined templates, prefixed by the
string “; defined templates are: “. If there are none, it returns the empty
string. Used to generate an error message.

func (*Template) Delims

  1. func (t *Template) Delims(left, right string) *Template

Delims sets the action delimiters to the specified strings, to be used in
subsequent calls to Parse, ParseFiles, or ParseGlob. Nested template definitions
will inherit the settings. An empty delimiter stands for the corresponding
default: {{ or }}. The return value is the template, so calls can be chained.

func (*Template) Execute

  1. func (t *Template) Execute(wr io.Writer, data interface{}) error

Execute applies a parsed template to the specified data object, writing the
output to wr. If an error occurs executing the template or writing its output,
execution stops, but partial results may already have been written to the output
writer. A template may be executed safely in parallel, although if parallel
executions share a Writer the output may be interleaved.

func (*Template) ExecuteTemplate

  1. func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error

ExecuteTemplate applies the template associated with t that has the given name
to the specified data object and writes the output to wr. If an error occurs
executing the template or writing its output, execution stops, but partial
results may already have been written to the output writer. A template may be
executed safely in parallel, although if parallel executions share a Writer the
output may be interleaved.

func (*Template) Funcs

  1. func (t *Template) Funcs(funcMap FuncMap) *Template

Funcs adds the elements of the argument map to the template’s function map. It
must be called before the template is parsed. It panics if a value in the map is
not a function with appropriate return type. However, it is legal to overwrite
elements of the map. The return value is the template, so calls can be chained.

func (*Template) Lookup

  1. func (t *Template) Lookup(name string) *Template

Lookup returns the template with the given name that is associated with t, or
nil if there is no such template.

func (*Template) Name

  1. func (t *Template) Name() string

Name returns the name of the template.

func (*Template) New

  1. func (t *Template) New(name string) *Template

New allocates a new HTML template associated with the given one and with the
same delimiters. The association, which is transitive, allows one template to
invoke another with a {{template}} action.

If a template with the given name already exists, the new HTML template will
replace it. The existing template will be reset and disassociated with t.

func (*Template) Option

  1. func (t *Template) Option(opt ...string) *Template

Option sets options for the template. Options are described by strings, either a
simple string or “key=value”. There can be at most one equals sign in an option
string. If the option string is unrecognized or otherwise invalid, Option
panics.

Known options:

missingkey: Control the behavior during execution if a map is indexed with a key
that is not present in the map.

  1. "missingkey=default" or "missingkey=invalid"
  2. The default behavior: Do nothing and continue execution.
  3. If printed, the result of the index operation is the string
  4. "<no value>".
  5. "missingkey=zero"
  6. The operation returns the zero value for the map type's element.
  7. "missingkey=error"
  8. Execution stops immediately with an error.

func (*Template) Parse

  1. func (t *Template) Parse(text string) (*Template, error)

Parse parses text as a template body for t. Named template definitions ({{define
…}} or {{block …}} statements) in text define additional templates
associated with t and are removed from the definition of t itself.

Templates can be redefined in successive calls to Parse, before the first use of
Execute on t or any associated template. A template definition with a body
containing only white space and comments is considered empty and will not
replace an existing template’s body. This allows using Parse to add new named
template definitions without overwriting the main template body.

func (*Template) ParseFiles

  1. func (t *Template) ParseFiles(filenames ...string) (*Template, error)

ParseFiles parses the named files and associates the resulting templates with t.
If an error occurs, parsing stops and the returned template is nil; otherwise it
is t. There must be at least one file.

When parsing multiple files with the same name in different directories, the
last one mentioned will be the one that results.

ParseFiles returns an error if t or any associated template has already been
executed.

func (*Template) ParseGlob

  1. func (t *Template) ParseGlob(pattern string) (*Template, error)

ParseGlob parses the template definitions in the files identified by the pattern
and associates the resulting templates with t. The pattern is processed by
filepath.Glob and must match at least one file. ParseGlob is equivalent to
calling t.ParseFiles with the list of files matched by the pattern.

When parsing multiple files with the same name in different directories, the
last one mentioned will be the one that results.

ParseGlob returns an error if t or any associated template has already been
executed.

func (*Template) Templates

  1. func (t *Template) Templates() []*Template

Templates returns a slice of the templates associated with t, including t
itself.

type URL

  1. type URL string

URL encapsulates a known safe URL or URL substring (see RFC 3986). A URL like
javascript:checkThatFormNotEditedBeforeLeavingPage() from a trusted source
should go in the page, but by default dynamic javascript: URLs are filtered
out since they are a frequently exploited injection vector.

Use of this type presents a security risk: the encapsulated content should come
from a trusted source, as it will be included verbatim in the template output.