package template

Import Path
	html/template (on golang.org and go.dev)

Dependency Relation
	imports 15 packages, and imported by 2 packages

Involved Source Files
	    attr.go
	    attr_string.go
	    content.go
	    context.go
	    css.go
	    delim_string.go
	d-> doc.go
	    element_string.go
	    error.go
	    escape.go
	    html.go
	    js.go
	    jsctx_string.go
	    state_string.go
	    template.go
	    transition.go
	    url.go
	    urlpart_string.go

Exported Type Names

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 risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.
type Error (struct) Error describes a problem encountered during template Escaping. Description string ErrorCode ErrorCode Line int Name string Node parse.Node (*T) Error() string *T : error
type ErrorCode int ErrorCode is a code for a kind of error. const ErrAmbigContext const ErrBadHTML const ErrBranchEnd const ErrEndContext const ErrNoSuchTemplate const ErrOutputContext const ErrPartialCharset const ErrPartialEscape const ErrPredefinedEscaper const ErrRangeLoopReentry const ErrSlashAmbig const OK
type FuncMap (map) 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". func (*Template).Funcs(funcMap FuncMap) *Template
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 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 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 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 verbatim in the template output.
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.
type Template (struct) Template is a specialized Template from "text/template" that produces a safe HTML document fragment. Tree *parse.Tree (*T) AddParseTree(name string, tree *parse.Tree) (*Template, error) (*T) Clone() (*Template, error) (*T) DefinedTemplates() string (*T) Delims(left, right string) *Template (*T) Execute(wr io.Writer, data interface{}) error (*T) ExecuteTemplate(wr io.Writer, name string, data interface{}) error (*T) Funcs(funcMap FuncMap) *Template (*T) Lookup(name string) *Template (*T) Name() string (*T) New(name string) *Template (*T) Option(opt ...string) *Template (*T) Parse(text string) (*Template, error) (*T) ParseFiles(filenames ...string) (*Template, error) (*T) ParseGlob(pattern string) (*Template, error) (*T) Templates() []*Template func Must(t *Template, err error) *Template func New(name string) *Template func ParseFiles(filenames ...string) (*Template, error) func ParseGlob(pattern string) (*Template, error) func (*Template).AddParseTree(name string, tree *parse.Tree) (*Template, error) func (*Template).Clone() (*Template, error) func (*Template).Delims(left, right string) *Template func (*Template).Funcs(funcMap FuncMap) *Template func (*Template).Lookup(name string) *Template func (*Template).New(name string) *Template func (*Template).Option(opt ...string) *Template func (*Template).Parse(text string) (*Template, error) func (*Template).ParseFiles(filenames ...string) (*Template, error) func (*Template).ParseGlob(pattern string) (*Template, error) func (*Template).Templates() []*Template func Must(t *Template, err error) *Template
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.
Exported Values
const ErrAmbigContext ErrorCode = 1 ErrAmbigContext: "... appears in an ambiguous context within a URL" Example: <a href=" {{if .C}} /path/ {{else}} /search?q= {{end}} {{.X}} "> Discussion: {{.X}} is in an ambiguous URL context since, depending on {{.C}}, it may be either a URL suffix or a query parameter. Moving {{.X}} into the condition removes the ambiguity: <a href="{{if .C}}/path/{{.X}}{{else}}/search?q={{.X}}">
const ErrBadHTML ErrorCode = 2 ErrBadHTML: "expected space, attr name, or end of tag, but got ...", "... in unquoted attr", "... in attribute name" Example: <a href = /search?q=foo> <href=foo> <form na<e=...> <option selected< Discussion: This is often due to a typo in an HTML element, but some runes are banned in tag names, attribute names, and unquoted attribute values because they can tickle parser ambiguities. Quoting all attributes is the best policy.
const ErrBranchEnd ErrorCode = 3 ErrBranchEnd: "{{if}} branches end in different contexts" Example: {{if .C}}<a href="{{end}}{{.X}} Discussion: Package html/template statically examines each path through an {{if}}, {{range}}, or {{with}} to escape any following pipelines. The example is ambiguous since {{.X}} might be an HTML text node, or a URL prefix in an HTML attribute. The context of {{.X}} is used to figure out how to escape it, but that context depends on the run-time value of {{.C}} which is not statically known. The problem is usually something like missing quotes or angle brackets, or can be avoided by refactoring to put the two contexts into different branches of an if, range or with. If the problem is in a {{range}} over a collection that should never be empty, adding a dummy {{else}} can help.
const ErrEndContext ErrorCode = 4 ErrEndContext: "... ends in a non-text context: ..." Examples: <div <div title="no close quote> <script>f() Discussion: Executed templates should produce a DocumentFragment of HTML. Templates that end without closing tags will trigger this error. Templates that should not be used in an HTML context or that produce incomplete Fragments should not be executed directly. {{define "main"}} <script>{{template "helper"}}</script> {{end}} {{define "helper"}} document.write(' <div title=" ') {{end}} "helper" does not produce a valid document fragment, so should not be Executed directly.
const ErrNoSuchTemplate ErrorCode = 5 ErrNoSuchTemplate: "no such template ..." Examples: {{define "main"}}<div {{template "attrs"}}>{{end}} {{define "attrs"}}href="{{.URL}}"{{end}} Discussion: Package html/template looks through template calls to compute the context. Here the {{.URL}} in "attrs" must be treated as a URL when called from "main", but you will get this error if "attrs" is not defined when "main" is parsed.
const ErrOutputContext ErrorCode = 6 ErrOutputContext: "cannot compute output context for template ..." Examples: {{define "t"}}{{if .T}}{{template "t" .T}}{{end}}{{.H}}",{{end}} Discussion: A recursive template does not end in the same context in which it starts, and a reliable output context cannot be computed. Look for typos in the named template. If the template should not be called in the named start context, look for calls to that template in unexpected contexts. Maybe refactor recursive templates to not be recursive.
const ErrPartialCharset ErrorCode = 7 ErrPartialCharset: "unfinished JS regexp charset in ..." Example: <script>var pattern = /foo[{{.Chars}}]/</script> Discussion: Package html/template does not support interpolation into regular expression literal character sets.
const ErrPartialEscape ErrorCode = 8 ErrPartialEscape: "unfinished escape sequence in ..." Example: <script>alert("\{{.X}}")</script> Discussion: Package html/template does not support actions following a backslash. This is usually an error and there are better solutions; for example <script>alert("{{.X}}")</script> should work, and if {{.X}} is a partial escape sequence such as "xA0", mark the whole sequence as safe content: JSStr(`\xA0`)
const ErrPredefinedEscaper ErrorCode = 11 ErrPredefinedEscaper: "predefined escaper ... disallowed in template" Example: <div class={{. | html}}>Hello<div> Discussion: Package html/template already contextually escapes all pipelines to produce HTML output safe against code injection. Manually escaping pipeline output using the predefined escapers "html" or "urlquery" is unnecessary, and may affect the correctness or safety of the escaped pipeline output in Go 1.8 and earlier. In most cases, such as the given example, this error can be resolved by simply removing the predefined escaper from the pipeline and letting the contextual autoescaper handle the escaping of the pipeline. In other instances, where the predefined escaper occurs in the middle of a pipeline where subsequent commands expect escaped input, e.g. {{.X | html | makeALink}} where makeALink does return `<a href="`+input+`">link</a>` consider refactoring the surrounding template to make use of the contextual autoescaper, i.e. <a href="{{.X}}">link</a> To ease migration to Go 1.9 and beyond, "html" and "urlquery" will continue to be allowed as the last command in a pipeline. However, if the pipeline occurs in an unquoted attribute value context, "html" is disallowed. Avoid using "html" and "urlquery" entirely in new templates.
const ErrRangeLoopReentry ErrorCode = 9 ErrRangeLoopReentry: "on range loop re-entry: ..." Example: <script>var x = [{{range .}}'{{.}},{{end}}]</script> Discussion: If an iteration through a range would cause it to end in a different context than an earlier pass, there is no single context. In the example, there is missing a quote, so it is not clear whether {{.}} is meant to be inside a JS string or in a JS value context. The second iteration would produce something like <script>var x = ['firstValue,'secondValue]</script>
const ErrSlashAmbig ErrorCode = 10 ErrSlashAmbig: '/' could start a division or regexp. Example: <script> {{if .C}}var x = 1{{end}} /-{{.N}}/i.test(x) ? doThis : doThat(); </script> Discussion: The example above could produce `var x = 1/-2/i.test(s)...` in which the first '/' is a mathematical division operator or it could produce `/-2/i.test(s)` in which the first '/' starts a regexp literal. Look for missing semicolons inside branches, and maybe add parentheses to make it clear which interpretation you intend.
func HTMLEscape(w io.Writer, b []byte) HTMLEscape writes to w the escaped HTML equivalent of the plain text data b.
func HTMLEscaper(args ...interface{}) string HTMLEscaper returns the escaped HTML equivalent of the textual representation of its arguments.
func HTMLEscapeString(s string) string HTMLEscapeString returns the escaped HTML equivalent of the plain text data s.
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(w io.Writer, b []byte) JSEscape writes to w the escaped JavaScript equivalent of the plain text data b.
func JSEscaper(args ...interface{}) string JSEscaper returns the escaped JavaScript equivalent of the textual representation of its arguments.
func JSEscapeString(s string) string JSEscapeString returns the escaped JavaScript equivalent of the plain text data s.
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"))
func New(name string) *Template New allocates a new HTML template with the given name.
const OK ErrorCode = 0 OK indicates the lack of an error.
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(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 directories, the last one mentioned will be the one that results.
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.