html/template
import "html/template"
Package template (html/template) implements data-driven templates for generating HTML output safe against code injection. It provides the same interface as [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 [text/template] so you can share it...
Go 1.26.1
Functions
func HTMLEscape(w io.Writer, b []byte)
HTMLEscape writes to w the escaped HTML equivalent of the plain text data b.
html/template/escape.go:976
func HTMLEscaper(args ...any) string
HTMLEscaper returns the escaped HTML equivalent of the textual representation of its arguments.
html/template/escape.go:987
func HTMLEscapeString(s string) string
HTMLEscapeString returns the escaped HTML equivalent of the plain text data s.
html/template/escape.go:981
func IsTrue(val any) 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.
html/template/template.go:483
func JSEscape(w io.Writer, b []byte)
JSEscape writes to w the escaped JavaScript equivalent of the plain text data b.
html/template/escape.go:992
func JSEscaper(args ...any) string
JSEscaper returns the escaped JavaScript equivalent of the textual representation of its arguments.
html/template/escape.go:1003
func JSEscapeString(s string) string
JSEscapeString returns the escaped JavaScript equivalent of the plain text data s.
html/template/escape.go:997
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 var t = template.Must(template.New("name").Parse("html"))
html/template/template.go:366
func New(name string) *Template
New allocates a new HTML template with the given name.
html/template/template.go:284
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 na...
html/template/template.go:382
func ParseFS(fs fs.FS, patterns ...string) (*Template, error)
ParseFS is like [ParseFiles] or [ParseGlob] but reads from the file system fs instead of the host operating system's file system. It accepts a list of glob patterns. (Note that most file names serve as glob patterns matching only themselves.)
html/template/template.go:491
func ParseGlob(pattern string) (*Template, error)
ParseGlob creates a new [Template] and parses the template definitions from the files identified by the pattern. The files are matched according to the semantics of filepath.Match, and the pattern 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 di...
html/template/template.go:447
func URLQueryEscaper(args ...any) string
URLQueryEscaper returns the escaped value of the textual representation of its arguments in a form suitable for embedding in a URL query.
html/template/escape.go:1009
Types
type CSS string
CSS encapsulates known safe content that matches any of: 1. The CSS3 stylesheet production, such as `p { color: purple }`. 2. The CSS3 rule production, such as `a[href=~"https:"].foo#bar`. 3. CSS3 declaration productions, such as `color: red; margin: 2px`. 4. The CSS3 value production, such as `rgba(0, 0, 255, 127)`. See https://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 ris...
html/template/content.go:25
type Error struct {
// ErrorCode describes the kind of error.
ErrorCode ErrorCode
// Node is the node that caused the problem, if known.
// If not nil, it overrides Name and Line.
Node parse.N...Error describes a problem encountered during template Escaping.
html/template/error.go:13
func (e *Error) Error() string
html/template/error.go:234
type ErrorCode int
ErrorCode is a code for a kind of error.
html/template/error.go:28
type FuncMap = template.FuncMap
html/template/template.go:331
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.
html/template/content.go:35
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.
html/template/content.go:43
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 i...
html/template/content.go:61
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: StringCharacter :: SourceCharacter but not `\` or LineTerminator | 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 ve...
html/template/content.go:74
type Srcset string
Srcset encapsulates a known safe srcset attribute (see https://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.
html/template/content.go:93
type Template struct {
// The underlying template's parse tree, updated to be HTML-safe.
Tree *parse.Tree
// contains filtered or unexported fields
}Template is a specialized Template from "text/template" that produces a safe HTML document fragment.
html/template/template.go:21
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.
html/template/template.go:217
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 [Template.Parse] in the copy will add templates to the copy but not to the original. [Template.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.
html/template/template.go:246
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.
html/template/template.go:171
func (t *Template) Delims(left string, right string) *Template
Delims sets the action delimiters to the specified strings, to be used in subsequent calls to [Template.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.
html/template/template.go:348
func (t *Template) Execute(wr io.Writer, data any) 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.
html/template/template.go:120
func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) 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.
html/template/template.go:134
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.
html/template/template.go:338
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.
html/template/template.go:355
func (t *Template) Name() string
Name returns the name of the template.
html/template/template.go:327
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.
html/template/template.go:304
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. "missingkey=default" or "missingkey=invalid" The default behavior: Do nothing and continue execution. If printed, the ...
html/template/template.go:76
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 [Template.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....
html/template/template.go:186
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.
html/template/template.go:394
func (t *Template) ParseFS(fs fs.FS, patterns ...string) (*Template, error)
ParseFS is like [Template.ParseFiles] or [Template.ParseGlob] but reads from the file system fs instead of the host operating system's file system. It accepts a list of glob patterns. (Note that most file names serve as glob patterns matching only themselves.)
html/template/template.go:499
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 files are matched according to the semantics of filepath.Match, and the pattern 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 ...
html/template/template.go:461
func (t *Template) Templates() []*Template
Templates returns a slice of the templates associated with t, including t itself.
html/template/template.go:46
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.
html/template/content.go:85