Documentation
¶
Overview ¶
Package template is muxt's template engine: a text/template parser that records source positions and parses HTML structure, and the execution engine for its trees. Package template/html builds an html/template-compatible API on it.
It is muxt's analysis and coverage engine, and its contextual escaping has documented gaps (see ExecuteTemplate); muxt's generated handlers render with the standard library's html/template, and this package must not be used to render untrusted data for a browser.
The packages are public so that the coverage pre-pass of muxt test-template-mutations can require them from the module under test, and so that tools can use them. They are versioned with the muxt command: go get github.com/typelate/htt@<version> gets the engine of muxt <version>. There is no stability promise beyond the command's own; any release may change their API.
Derived in part from the Go standard library; see NOTICE.txt at the repository root.
Index ¶
- Variables
- func AnnotateHTMLContexts(root Node)
- func DefinedTrees(root *Tree, treeSet map[string]*Tree) map[string]*Tree
- func EscapeCSS(s string) string
- func EscapeJS(s string) string
- func ExecuteDocument(tree *Tree, data any, opts ...Option) (*html.Node, error)
- func ExecuteElement(tree *Tree, elem *HTMLElementNode, data any, opts ...Option) (*html.Node, error)
- func ExecuteTemplate(w io.Writer, tree *Tree, data any, opts ...Option) error
- func Extract(src *Tree) iter.Seq2[string, *Tree]
- func FilterSrcset(s string) string
- func FilterURL(s string) string
- func IsEmptyTree(n Node) bool
- func IsJSEventAttr(attr string) bool
- func IsRawTextElement(tag string) bool
- func IsTrue(val any) (truth, ok bool)
- func IsURLAttr(attr string) bool
- func IsVoidElement(tag string) bool
- func Walk(tree *Tree, fn func(*Tree, Node))
- func WalkPath(tree *Tree, fn func(t *Tree, path []Node, n Node))
- type ActionNode
- type BlockNode
- type BoolNode
- type BranchNode
- type BreakNode
- type ChainNode
- type CommandNode
- type CommentNode
- type ContinueNode
- type CoverProfile
- type DefineNode
- type Diagnostic
- type DiagnosticCode
- type Diagnostics
- type DotNode
- type ExecError
- type FieldNode
- type FindTreeFunc
- type FuncMap
- type HTMLAttributeNode
- type HTMLCommentNode
- type HTMLContext
- type HTMLDoctypeNode
- type HTMLDocumentFragmentNode
- type HTMLElementNode
- type IdentifierNode
- type IfNode
- type ListNode
- type MissingKeyMode
- type NilNode
- type Node
- type NumberNode
- type Option
- type ParseError
- type PipeNode
- type Position
- type RangeNode
- type Severity
- type StringNode
- type Template
- func (t *Template[S]) AddParseTree(name string, tree *Tree) (*Template[S], error)
- func (t *Template[S]) Delimiters(left, right string) *Template[S]
- func (t *Template[S]) FindTree(name string) (*Tree, bool)
- func (t *Template[S]) Functions(functions map[string]S) *Template[S]
- func (t *Template[S]) IsText() bool
- func (t *Template[S]) Lookup(name string) *Template[S]
- func (t *Template[S]) Name() string
- func (t *Template[S]) Names() []string
- func (t *Template[S]) Option(opt ...string) (*Template[S], error)
- func (t *Template[S]) Parse(text string) (*Template[S], error)
- func (t *Template[S]) ParseOptions() lex.Options
- func (t *Template[S]) SkipFuncCheck() *Template[S]
- func (t *Template[S]) Tree() *Tree
- type TemplateNode
- type TextNode
- type Tree
- type TreeFinder
- type Trust
- type TrustFunc
- type VariableNode
- type WithNode
Constants ¶
This section is empty.
Variables ¶
var FormattingElements = map[string]bool{ "a": true, "b": true, "big": true, "code": true, "em": true, "font": true, "i": true, "nobr": true, "s": true, "small": true, "strike": true, "strong": true, "tt": true, "u": true, }
FormattingElements is the WHATWG §13.2.4.2 set subject to the adoption agency algorithm (§13.2.6.4.7).
var ImpliedEndTagElements = map[string]bool{ "dd": true, "dt": true, "li": true, "optgroup": true, "option": true, "p": true, "rb": true, "rp": true, "rt": true, "rtc": true, "caption": true, "colgroup": true, "tbody": true, "td": true, "tfoot": true, "th": true, "thead": true, "tr": true, }
ImpliedEndTagElements is the WHATWG §13.2.6.3 "generate implied end tags" set plus the "thoroughly" additions: elements whose end tags authors may legally omit.
Functions ¶
func AnnotateHTMLContexts ¶
func AnnotateHTMLContexts(root Node)
AnnotateHTMLContexts walks the tree and sets HTMLContext on each ActionNode based on its structural position in the AST.
func DefinedTrees ¶
DefinedTrees returns the trees a parse defined, by name, as text/template's set would hold them: root is the tree ParseTree returned and treeSet the tree set it was given, which the parser filled with the top-level tree and each define and block it kept, applying text/template's rule that a definition replaces an empty one and never one that is not empty.
A define's tree is the one Extract builds for it, which carries the diagnostics recorded in its body; a block's and the top-level tree are the parser's own.
func ExecuteDocument ¶
ExecuteDocument executes an HTML template tree, returning an *html.Node (DocumentNode). The tree's root must contain an HTMLDocumentFragmentNode. This returns the DOM tree directly without rendering to a writer.
func ExecuteElement ¶
func ExecuteElement(tree *Tree, elem *HTMLElementNode, data any, opts ...Option) (*html.Node, error)
ExecuteElement evaluates an HTMLElementNode against data, returning an *html.Node. This enables DOM interop with libraries like Cascadia and github.com/typelate/dom.
func ExecuteTemplate ¶
ExecuteTemplate executes a template tree, writing output to w. For HTML trees (root contains HTMLDocumentFragmentNode), it builds an html.Node intermediate representation and uses html.Render. For plain text trees, it writes directly like text/template.
ExecuteTemplate, ExecuteDocument and ExecuteElement are muxt's static-analysis and coverage engine: they run templates so that tests and tooling can observe what a template produces and which parts of it ran. They are not safe for serving HTTP responses; serve with html/template. Their contextual escaping is known to fall short of html/template's in three places:
- An action in attribute-name position (<div {{.Name}}="x">, data-{{.Key}}="x") is in a tag the parser reads as text, so the tag, the action's output included, is written as escaped HTML text (<div ...>) rather than as a tag with a filtered attribute name.
- A text (non-HTML) sub-template called from an HTML template is executed without the caller's escaping context.
- A style or srcdoc attribute's value is not escaped for the CSS or HTML document it holds.
func Extract ¶
Extract walks the parsed AST and yields {{define}} nodes (DefineNode) as separate trees. Each yielded pair is (template name, *Tree). The source tree itself is not yielded — only defines found within it.
func FilterSrcset ¶
FilterSrcset is the exported form of filterSrcset for testing.
func IsEmptyTree ¶
IsEmptyTree reports whether this tree (node) is empty of everything but space or comments.
func IsJSEventAttr ¶
IsJSEventAttr reports whether the named attribute is a JavaScript event handler, meaning an interpolated value is JS-escaped. It is the exported form of the classifier the escaper uses.
func IsRawTextElement ¶
IsRawTextElement reports whether the named element holds raw text whose contents are not HTML-escaped. Exported for tooling such as the LSP.
func IsTrue ¶
IsTrue reports whether the value is 'true', in the sense of not the zero of its type, and whether the value is valid. It is for use by packages that wrap htt.
func IsURLAttr ¶
IsURLAttr reports whether the named attribute typically holds a URL, meaning an interpolated value is filtered for dangerous schemes. It is the exported form of the classifier the escaper uses, so tooling (such as the LSP) can describe escaping without drifting from it.
func IsVoidElement ¶
IsVoidElement reports whether the named element is a void element (no closing tag). Exported for tooling such as the LSP.
func Walk ¶
Walk traverses the tree in source order, pre-order, calling fn for each node. It is a thin wrapper over WalkPath.
func WalkPath ¶
WalkPath traverses like Walk but also passes the stack of ancestor nodes, outermost first. Branch nodes (IfNode, RangeNode, WithNode) and list nodes appear in the path so callers can observe control flow between elements. fn must not retain path after returning; the backing array is reused.
Types ¶
type ActionNode ¶
type ActionNode struct {
Line int // The line number in the input. Deprecated: Kept for compatibility.
Pipe *PipeNode // The pipeline in the action.
HTMLContext *HTMLContext // Set by Template.Parse / AddParseTree; nil in non-HTML mode.
TrimLeft bool // {{- was used
TrimRight bool // -}} was used
// contains filtered or unexported fields
}
ActionNode holds an action (something bounded by delimiters). Control actions have their own nodes; ActionNode represents simple ones such as field evaluations and parenthesized pipelines.
func (*ActionNode) End ¶
func (a *ActionNode) End() lex.Pos
func (ActionNode) Parent ¶
func (n ActionNode) Parent() Node
Parent returns the node's lexical parent, or nil for a root.
A DefineNode and BlockNode are detached roots: their Parent is nil even though they are written inside another template's source. The logical parents of a define or block body are the {{template}} and {{block}} call sites that invoke it, which are resolved by callers rather than recorded here.
func (*ActionNode) Start ¶
func (a *ActionNode) Start() lex.Pos
func (*ActionNode) String ¶
func (a *ActionNode) String() string
type BlockNode ¶
type BlockNode struct {
Line int // The line number in the input.
Name string // The name of the block template (unquoted).
Pipe *PipeNode // The pipeline to evaluate as dot for the block.
Body *ListNode // The body of the block.
StartTrimLeft bool // {{- on block opener
StartTrimRight bool // -}} on block opener
EndTrimLeft bool // {{- on end
EndTrimRight bool // -}} on end
// contains filtered or unexported fields
}
BlockNode represents a {{block "name" pipeline}}...{{end}} kept inline in the AST. Like DefineNode it retains the body in the source tree; Extract() pulls it out for execution. Unlike DefineNode it carries a Pipe (like TemplateNode) that evaluates to dot for the block body.
func (*BlockNode) Call ¶
func (b *BlockNode) Call() *TemplateNode
Call returns the {{template}} invocation text/template makes of a block: a call of the template named Name, with Pipe as its dot, written where the block is. The body is that template's default definition, which a later define of the same name replaces, so a checker or walker following the invocation reaches whichever definition the set kept. It spans the whole block clause and is the same node on every call.
func (BlockNode) Parent ¶
func (n BlockNode) Parent() Node
Parent returns the node's lexical parent, or nil for a root.
A DefineNode and BlockNode are detached roots: their Parent is nil even though they are written inside another template's source. The logical parents of a define or block body are the {{template}} and {{block}} call sites that invoke it, which are resolved by callers rather than recorded here.
type BoolNode ¶
type BoolNode struct {
True bool // The value of the boolean constant.
// contains filtered or unexported fields
}
BoolNode holds a boolean constant.
type BranchNode ¶
type BranchNode struct {
Line int // The line number in the input. Deprecated: Kept for compatibility.
Pipe *PipeNode // The pipeline to be evaluated.
List *ListNode // What to execute if the value is non-empty.
ElseList *ListNode // What to execute if the value is empty (nil if absent).
StartTrimLeft bool // {{- on opener
StartTrimRight bool // -}} on opener
ElseTrimLeft bool // {{- on else
ElseTrimRight bool // -}} on else
EndTrimLeft bool // {{- on end
EndTrimRight bool // -}} on end
// contains filtered or unexported fields
}
BranchNode is the common representation of if, range, and with.
func (*BranchNode) ElseChain ¶
func (b *BranchNode) ElseChain() *BranchNode
ElseChain returns the branch the source chained onto b's else, as in {{if .A}}a{{else if .B}}b{{end}}, or nil when b has no else or the else is a plain {{else}} (even one holding only a nested branch). The chained branch starts at the {{else if}} / {{else with}} action, so its source opener is that action, and it holds the shared {{end}}.
func (*BranchNode) End ¶
func (b *BranchNode) End() lex.Pos
func (BranchNode) Parent ¶
func (n BranchNode) Parent() Node
Parent returns the node's lexical parent, or nil for a root.
A DefineNode and BlockNode are detached roots: their Parent is nil even though they are written inside another template's source. The logical parents of a define or block body are the {{template}} and {{block}} call sites that invoke it, which are resolved by callers rather than recorded here.
func (*BranchNode) Start ¶
func (b *BranchNode) Start() lex.Pos
func (*BranchNode) String ¶
func (b *BranchNode) String() string
type BreakNode ¶
type BreakNode struct {
Line int
TrimLeft bool // {{- was used
TrimRight bool // -}} was used
// contains filtered or unexported fields
}
BreakNode represents a {{break}} action.
func (BreakNode) Parent ¶
func (n BreakNode) Parent() Node
Parent returns the node's lexical parent, or nil for a root.
A DefineNode and BlockNode are detached roots: their Parent is nil even though they are written inside another template's source. The logical parents of a define or block body are the {{template}} and {{block}} call sites that invoke it, which are resolved by callers rather than recorded here.
type ChainNode ¶
type ChainNode struct {
Node Node
Field []string // The identifiers in lexical order.
// contains filtered or unexported fields
}
ChainNode holds a term followed by a chain of field accesses (identifier starting with '.'). The names may be chained ('.x.y'). The periods are dropped from each ident.
type CommandNode ¶
type CommandNode struct {
Args []Node // Arguments in lexical order: Identifier, field, or constant.
// contains filtered or unexported fields
}
CommandNode holds a command (a pipeline inside an evaluating action).
func (*CommandNode) End ¶
func (c *CommandNode) End() lex.Pos
func (*CommandNode) Start ¶
func (c *CommandNode) Start() lex.Pos
func (*CommandNode) String ¶
func (c *CommandNode) String() string
type CommentNode ¶
type CommentNode struct {
Text string // Comment text.
TrimLeft bool // {{- was used
TrimRight bool // -}} was used
// contains filtered or unexported fields
}
CommentNode holds a comment.
func (*CommentNode) End ¶
func (c *CommentNode) End() lex.Pos
func (CommentNode) Parent ¶
func (n CommentNode) Parent() Node
Parent returns the node's lexical parent, or nil for a root.
A DefineNode and BlockNode are detached roots: their Parent is nil even though they are written inside another template's source. The logical parents of a define or block body are the {{template}} and {{block}} call sites that invoke it, which are resolved by callers rather than recorded here.
func (*CommentNode) Start ¶
func (c *CommentNode) Start() lex.Pos
func (*CommentNode) String ¶
func (c *CommentNode) String() string
type ContinueNode ¶
type ContinueNode struct {
Line int
TrimLeft bool // {{- was used
TrimRight bool // -}} was used
// contains filtered or unexported fields
}
ContinueNode represents a {{continue}} action.
func (*ContinueNode) End ¶
func (c *ContinueNode) End() lex.Pos
func (ContinueNode) Parent ¶
func (n ContinueNode) Parent() Node
Parent returns the node's lexical parent, or nil for a root.
A DefineNode and BlockNode are detached roots: their Parent is nil even though they are written inside another template's source. The logical parents of a define or block body are the {{template}} and {{block}} call sites that invoke it, which are resolved by callers rather than recorded here.
func (*ContinueNode) Start ¶
func (c *ContinueNode) Start() lex.Pos
func (*ContinueNode) String ¶
func (c *ContinueNode) String() string
type CoverProfile ¶
type CoverProfile struct {
// contains filtered or unexported fields
}
CoverProfile collects coverage information during template execution.
Usage: create a CoverProfile, pass it to execute via WithCoverProfile, then execute templates. Trees are added automatically during execution. After execution, call WriteTo to produce a Go coverage profile.
Coverage counters are embedded atomic.Int64 fields on AST nodes. Execution increments them via .Add(1); WriteTo reads them via .Load().
func (*CoverProfile) AddTree ¶
func (cp *CoverProfile) AddTree(tree *Tree)
AddTree registers a tree for coverage reporting. Safe to call multiple times for the same tree (idempotent). Must be called before or during execution so WriteTo includes the tree's counters.
func (*CoverProfile) Init ¶
func (cp *CoverProfile) Init(tree *Tree)
Init registers the tree for coverage. Called by the execution engine.
func (*CoverProfile) WriteNewlyCovered ¶
WriteNewlyCovered writes a line for each executed block of the profile's trees that is not yet in written, then adds those blocks to written. It is for exporting coverage incrementally: mode set is monotone, so a block needs writing only once, the first time its counter is nonzero.
Lines are in WriteTo's format, without the mode line, one block per coverable node (not collapsed, since a neighbor reached later would change a collapsed range) and with count 1. A block is identified by its parse name and position range, so a reparsed tree whose blocks were already written writes nothing. The lines go to w in one Write; if it fails, nothing is added to written.
type DefineNode ¶
type DefineNode struct {
Line int // The line number in the input.
Name string // The name of the defined template (unquoted).
Body *ListNode // The body of the define.
StartTrimLeft bool // {{- on define opener
StartTrimRight bool // -}} on define opener
EndTrimLeft bool // {{- on end
EndTrimRight bool // -}} on end
// contains filtered or unexported fields
}
DefineNode represents a {{define "name"}}...{{end}} kept inline in the AST. In standard text/template parsing, defines are extracted into separate trees during parsing. DefineNode allows the parser to retain the define in the source-faithful AST; Extract() can later pull them out for execution.
func (*DefineNode) End ¶
func (d *DefineNode) End() lex.Pos
func (DefineNode) Parent ¶
func (n DefineNode) Parent() Node
Parent returns the node's lexical parent, or nil for a root.
A DefineNode and BlockNode are detached roots: their Parent is nil even though they are written inside another template's source. The logical parents of a define or block body are the {{template}} and {{block}} call sites that invoke it, which are resolved by callers rather than recorded here.
func (*DefineNode) Start ¶
func (d *DefineNode) Start() lex.Pos
func (*DefineNode) String ¶
func (d *DefineNode) String() string
type Diagnostic ¶
type Diagnostic struct {
Pos lex.Pos
End lex.Pos
Severity Severity
Code DiagnosticCode
Message string
}
Diagnostic is a non-fatal structural finding: the tree still faithfully represents the source, but a browser's tree construction would diverge from the source's literal nesting at this position.
func (Diagnostic) String ¶
func (d Diagnostic) String() string
type DiagnosticCode ¶
type DiagnosticCode string
DiagnosticCode identifies a class of structural finding. Codes are stable identifiers for tests, suppression, and LSP mapping.
const ( DiagUnclosedElement DiagnosticCode = "unclosed-element" DiagOrphanEndTag DiagnosticCode = "orphan-end-tag" DiagMisnestedTag DiagnosticCode = "misnested-tag" // adoption agency (WHATWG §13.2.6.4.7) DiagFosteredContent DiagnosticCode = "fostered-content" // foster parenting (§13.2.6.4.9) DiagNestedForm DiagnosticCode = "nested-form" // §13.2.6.4.7 form pointer DiagAutoClosed DiagnosticCode = "auto-closed" // implied end tags (§13.2.6.3) DiagNestedLink DiagnosticCode = "nested-link" DiagNestedButton DiagnosticCode = "nested-button" DiagUnknownCSSProperty DiagnosticCode = "unknown-css-property" DiagInvalidCSSValue DiagnosticCode = "invalid-css-value" DiagUnknownCSSAtRule DiagnosticCode = "unknown-css-at-rule" DiagUndefinedCSSCustomProperty DiagnosticCode = "undefined-css-custom-property" DiagUnusedCSSRule DiagnosticCode = "unused-css-rule" DiagUnusedCSSSelector DiagnosticCode = "unused-css-selector" )
type Diagnostics ¶
type Diagnostics []Diagnostic
func (Diagnostics) SortByPos ¶
func (ds Diagnostics) SortByPos()
type DotNode ¶
type DotNode struct {
// contains filtered or unexported fields
}
DotNode holds the special identifier '.'.
type ExecError ¶
ExecError is the custom error type returned when Execute fails. It provides the name of the template in which the error occurred.
type FieldNode ¶
type FieldNode struct {
Ident []string // The identifiers in lexical order.
// contains filtered or unexported fields
}
FieldNode holds a field (identifier starting with '.'). The names may be chained ('.x.y'). The period is dropped from each ident.
type FindTreeFunc ¶
FindTreeFunc adapts a function to the TreeFinder interface.
type FuncMap ¶
FuncMap is the type of the map defining the mapping from names to functions. Each value must be a function with a single return value, or a function with two return values where the second is an error.
type HTMLAttributeNode ¶
type HTMLAttributeNode struct {
Namespace string // Optional namespace (e.g., "xlink" in "xlink:href").
Key []Node // Attribute name parts (supports dynamic names).
Value []Node // Attribute value parts (supports dynamic values).
HasValue bool // Distinguishes `disabled` from `disabled=""`.
// contains filtered or unexported fields
}
HTMLAttributeNode represents an HTML attribute. Key and Value are slices of Node to support dynamic content (interleaved TextNode + ActionNode). HasValue distinguishes `disabled` from `disabled=""`.
func (*HTMLAttributeNode) End ¶
func (n *HTMLAttributeNode) End() lex.Pos
func (HTMLAttributeNode) Parent ¶
func (n HTMLAttributeNode) Parent() Node
Parent returns the node's lexical parent, or nil for a root.
A DefineNode and BlockNode are detached roots: their Parent is nil even though they are written inside another template's source. The logical parents of a define or block body are the {{template}} and {{block}} call sites that invoke it, which are resolved by callers rather than recorded here.
func (*HTMLAttributeNode) Start ¶
func (n *HTMLAttributeNode) Start() lex.Pos
func (*HTMLAttributeNode) String ¶
func (n *HTMLAttributeNode) String() string
type HTMLCommentNode ¶
type HTMLCommentNode struct {
Children []Node // Comment content: TextNode and ActionNode interleaved.
// contains filtered or unexported fields
}
HTMLCommentNode represents an HTML comment. Children (not Text) supports template actions inside comments: <!-- version: {{.Version}} -->
func (*HTMLCommentNode) End ¶
func (n *HTMLCommentNode) End() lex.Pos
func (HTMLCommentNode) Parent ¶
func (n HTMLCommentNode) Parent() Node
Parent returns the node's lexical parent, or nil for a root.
A DefineNode and BlockNode are detached roots: their Parent is nil even though they are written inside another template's source. The logical parents of a define or block body are the {{template}} and {{block}} call sites that invoke it, which are resolved by callers rather than recorded here.
func (*HTMLCommentNode) Start ¶
func (n *HTMLCommentNode) Start() lex.Pos
func (*HTMLCommentNode) String ¶
func (n *HTMLCommentNode) String() string
type HTMLContext ¶
type HTMLContext struct {
State string // "text", "attr", "comment"
Element string // element name (e.g., "script", "style", "p") or ""
Attr string // attribute name (e.g., "href", "onclick", "class") or ""
// JSContext is set when State is "text" and Element is "script". It is
// "expr" outside of any string/template literal, "str" inside ' or "
// strings, "tpl" inside backtick template literals, "regex" inside a
// regex literal, or "comment" inside a JS comment.
//
// A ${...} interpolation inside a template literal is an expression
// position, so it reports "expr", not "tpl".
JSContext string
}
HTMLContext represents the escaping context at a template action node. This mirrors the key fields of html/template's context type.
type HTMLDoctypeNode ¶
type HTMLDoctypeNode struct {
Text string // The raw DOCTYPE text, e.g. "<!DOCTYPE html>".
// contains filtered or unexported fields
}
HTMLDoctypeNode represents an HTML DOCTYPE declaration.
func (*HTMLDoctypeNode) End ¶
func (n *HTMLDoctypeNode) End() lex.Pos
func (HTMLDoctypeNode) Parent ¶
func (n HTMLDoctypeNode) Parent() Node
Parent returns the node's lexical parent, or nil for a root.
A DefineNode and BlockNode are detached roots: their Parent is nil even though they are written inside another template's source. The logical parents of a define or block body are the {{template}} and {{block}} call sites that invoke it, which are resolved by callers rather than recorded here.
func (*HTMLDoctypeNode) Start ¶
func (n *HTMLDoctypeNode) Start() lex.Pos
func (*HTMLDoctypeNode) String ¶
func (n *HTMLDoctypeNode) String() string
type HTMLDocumentFragmentNode ¶
type HTMLDocumentFragmentNode struct {
Children []Node
// contains filtered or unexported fields
}
HTMLDocumentFragmentNode is the top-level container for HTML+template content. It wraps a flat list of top-level HTML and template nodes without imposing well-formedness or mutating the tree. Structurally similar to ListNode, but ListNode is used in template contexts (if/range/with bodies), while DocumentFragment is the top-level container for HTML+template content.
func (*HTMLDocumentFragmentNode) End ¶
func (n *HTMLDocumentFragmentNode) End() lex.Pos
func (HTMLDocumentFragmentNode) Parent ¶
func (n HTMLDocumentFragmentNode) Parent() Node
Parent returns the node's lexical parent, or nil for a root.
A DefineNode and BlockNode are detached roots: their Parent is nil even though they are written inside another template's source. The logical parents of a define or block body are the {{template}} and {{block}} call sites that invoke it, which are resolved by callers rather than recorded here.
func (*HTMLDocumentFragmentNode) Start ¶
func (n *HTMLDocumentFragmentNode) Start() lex.Pos
func (*HTMLDocumentFragmentNode) String ¶
func (n *HTMLDocumentFragmentNode) String() string
type HTMLElementNode ¶
type HTMLElementNode struct {
TagName string // Must be static — dynamic tag names are an error.
Attr []Node // Attribute list: HTMLAttributeNode, ActionNode, IfNode, RangeNode, etc.
Children []Node // Child nodes in lexical order.
Void bool // True for void elements (br, hr, img, etc.).
Closed bool // True if the parser found a matching end tag.
Misnested bool // True if an ancestor's end tag closed it first; a misnested-tag diagnostic reports it.
AttrStart lex.Pos // Position after tag name (start of attribute region).
AttrEnd lex.Pos // Position after '>' closing the opening tag.
EndTagStart lex.Pos // Position of '<' in '</tag>'.
// contains filtered or unexported fields
}
HTMLElementNode represents an HTML element in the parse tree. TagName must be a static string (dynamic tag names are an error, matching html/template's constraint). Attr may contain HTMLAttributeNode, ActionNode, IfNode, RangeNode, etc. Children contains the element's content nodes.
func (*HTMLElementNode) End ¶
func (n *HTMLElementNode) End() lex.Pos
func (HTMLElementNode) Parent ¶
func (n HTMLElementNode) Parent() Node
Parent returns the node's lexical parent, or nil for a root.
A DefineNode and BlockNode are detached roots: their Parent is nil even though they are written inside another template's source. The logical parents of a define or block body are the {{template}} and {{block}} call sites that invoke it, which are resolved by callers rather than recorded here.
func (*HTMLElementNode) Start ¶
func (n *HTMLElementNode) Start() lex.Pos
func (*HTMLElementNode) String ¶
func (n *HTMLElementNode) String() string
type IdentifierNode ¶
type IdentifierNode struct {
Ident string // The identifier's name.
// contains filtered or unexported fields
}
IdentifierNode holds an identifier.
func NewIdentifier ¶
func NewIdentifier(tr *Tree, start, end lex.Pos, ident string) *IdentifierNode
NewIdentifier returns a new IdentifierNode with the given identifier name.
func (*IdentifierNode) End ¶
func (i *IdentifierNode) End() lex.Pos
func (*IdentifierNode) Start ¶
func (i *IdentifierNode) Start() lex.Pos
func (*IdentifierNode) String ¶
func (i *IdentifierNode) String() string
type IfNode ¶
type IfNode struct {
BranchNode
}
IfNode represents an {{if}} action and its commands.
func (IfNode) Parent ¶
func (n IfNode) Parent() Node
Parent returns the node's lexical parent, or nil for a root.
A DefineNode and BlockNode are detached roots: their Parent is nil even though they are written inside another template's source. The logical parents of a define or block body are the {{template}} and {{block}} call sites that invoke it, which are resolved by callers rather than recorded here.
type ListNode ¶
type ListNode struct {
Nodes []Node // The element nodes in lexical order.
// contains filtered or unexported fields
}
ListNode holds a sequence of nodes.
func (ListNode) Parent ¶
func (n ListNode) Parent() Node
Parent returns the node's lexical parent, or nil for a root.
A DefineNode and BlockNode are detached roots: their Parent is nil even though they are written inside another template's source. The logical parents of a define or block body are the {{template}} and {{block}} call sites that invoke it, which are resolved by callers rather than recorded here.
type MissingKeyMode ¶
type MissingKeyMode int
MissingKeyMode controls how missing map keys and struct fields are handled.
const ( // MissingKeyInvalid is the default: missing struct fields are an error, // missing map keys return the zero value. MissingKeyInvalid MissingKeyMode = iota // MissingKeyZero causes missing struct fields and map keys to return // the zero value instead of an error. MissingKeyZero // MissingKeyError causes both missing struct fields and missing map // keys to return an error. MissingKeyError )
type NilNode ¶
type NilNode struct {
// contains filtered or unexported fields
}
NilNode holds the special identifier 'nil' representing an untyped nil constant.
type Node ¶
type Node interface {
String() string
Start() lex.Pos // byte position of start of node in full original input string
End() lex.Pos // byte position of end of node (exclusive)
// contains filtered or unexported methods
}
A Node is an element in the parse tree. The interface is trivial. The interface contains an unexported method so that only types local to this package can satisfy it.
type NumberNode ¶
type NumberNode struct {
IsInt bool // Number has an integral value.
IsUint bool // Number has an unsigned integral value.
IsFloat bool // Number has a floating-point value.
IsComplex bool // Number is complex.
Int64 int64 // The signed integer value.
Uint64 uint64 // The unsigned integer value.
Float64 float64 // The floating-point value.
Complex128 complex128 // The complex value.
Text string // The original textual representation from the input.
// contains filtered or unexported fields
}
NumberNode holds a number: signed or unsigned integer, float, or complex. The value is parsed and stored under all the types that can represent the value. This simulates in a small amount of code the behavior of Go's ideal constants.
func (NumberNode) End ¶
func (n NumberNode) End() lex.Pos
func (NumberNode) Start ¶
func (n NumberNode) Start() lex.Pos
func (NumberNode) String ¶
func (n NumberNode) String() string
type Option ¶
type Option func(*config)
Option configures template execution.
func WithCoverProfile ¶
func WithCoverProfile(cp *CoverProfile) Option
WithCoverProfile enables coverage profiling during template execution.
func WithFinder ¶
func WithFinder(finder TreeFinder) Option
WithFinder provides a TreeFinder for resolving {{template}} calls.
func WithMissingKey ¶
func WithMissingKey(mode MissingKeyMode) Option
WithMissingKey sets the behavior for missing map keys and struct fields.
type ParseError ¶
type ParseError struct {
// contains filtered or unexported fields
}
ParseError is a template parse failure located at a byte span in the template text. Its Error string keeps the historical "template: <name>:<line>: <message>" form, so callers and tests that match on it are unaffected; the Unwrap, Position, and EndPosition methods let tooling place a diagnostic and read the position-free message without parsing that string.
func (*ParseError) EndPosition ¶
func (e *ParseError) EndPosition() token.Position
EndPosition returns the exclusive end of the failing token, the companion to Position for a ranged diagnostic.
func (*ParseError) Error ¶
func (e *ParseError) Error() string
func (*ParseError) Position ¶
func (e *ParseError) Position() token.Position
Position returns the start of the failing token as a token.Position; its Offset is the byte offset into the template text.
func (*ParseError) Unwrap ¶
func (e *ParseError) Unwrap() error
Unwrap returns the bare cause — the message without the location prefix.
type PipeNode ¶
type PipeNode struct {
Line int // The line number in the input. Deprecated: Kept for compatibility.
IsAssign bool // The variables are being assigned, not declared.
Decl []*VariableNode // Variables in lexical order.
Commands []*CommandNode // The commands in lexical order.
// contains filtered or unexported fields
}
PipeNode holds a pipeline with optional declaration
func (*PipeNode) HeadCommands ¶
func (p *PipeNode) HeadCommands() []*CommandNode
HeadCommands returns p's commands as text/template evaluates them: when the first command is a whole parenthesized pipeline that declares no variables, with no arguments after it, that pipeline's commands take its place, repeatedly. {{if (and .A .B)}} runs as {{if and .A .B}} and {{template "x" (.)}} as {{template "x" .}}, since evaluating such a command evaluates the inner pipeline and goes on with its value.
Parentheses anywhere else are kept, because the evaluator treats them differently: an argument, (.X) in {{print (.X)}}; a later stage, {{.X | (print)}}; one followed by a field chain, {{(.X).Y}}; and one that declares a variable, {{($y := .X)}}. p's declarations do not matter. HeadCommands does not modify p; when it replaces nothing the result is p.Commands itself.
type RangeNode ¶
type RangeNode struct {
BranchNode
}
RangeNode represents a {{range}} action and its commands.
func (RangeNode) Parent ¶
func (n RangeNode) Parent() Node
Parent returns the node's lexical parent, or nil for a root.
A DefineNode and BlockNode are detached roots: their Parent is nil even though they are written inside another template's source. The logical parents of a define or block body are the {{template}} and {{block}} call sites that invoke it, which are resolved by callers rather than recorded here.
type StringNode ¶
type StringNode struct {
Quoted string // The original text of the string, with quotes.
Text string // The string, after quote processing.
// contains filtered or unexported fields
}
StringNode holds a string constant. The value has been "unquoted".
func (*StringNode) End ¶
func (s *StringNode) End() lex.Pos
func (*StringNode) Start ¶
func (s *StringNode) Start() lex.Pos
func (*StringNode) String ¶
func (s *StringNode) String() string
type Template ¶
type Template[Signature any] struct { // contains filtered or unexported fields }
func New ¶
New returns a template set that parses as html/template does: its trees hold HTML structure and are executed in HTML mode.
func NewText ¶
NewText returns a template set that parses as text/template does: its trees are text and actions, with no HTML structure, so text such as JSON or prose with a '<' in it parses as it does with text/template.
func (*Template[S]) AddParseTree ¶
func (*Template[S]) Delimiters ¶
func (*Template[S]) Names ¶
Names returns the names of every template in the associated set, sorted. Tooling (such as LSP completion) uses it to offer the targets of {{template}} / {{block}} invocations.
func (*Template[S]) ParseOptions ¶
ParseOptions are the lexer options Parse parses text with: the set's delimiters, HTML structure unless the set is a text/template set, break and continue as keywords unless the set registers functions of those names, and, unless SkipFuncCheck was called, a call of a function that is neither registered nor a builtin as a parse error, as in text/template.
func (*Template[S]) SkipFuncCheck ¶
SkipFuncCheck makes Parse accept a call of a function that is not defined, as text/template/parse's SkipFuncCheck mode does, so that the call reaches the type checker. It returns t.
type TemplateNode ¶
type TemplateNode struct {
Line int // The line number in the input. Deprecated: Kept for compatibility.
Name string // The name of the template (unquoted).
Pipe *PipeNode // The command to evaluate as dot for the template.
HTMLContext *HTMLContext // Set by AnnotateHTMLContexts; nil in non-HTML mode.
TrimLeft bool // {{- was used
TrimRight bool // -}} was used
// contains filtered or unexported fields
}
TemplateNode represents a {{template}} action.
func (*TemplateNode) End ¶
func (t *TemplateNode) End() lex.Pos
func (TemplateNode) Parent ¶
func (n TemplateNode) Parent() Node
Parent returns the node's lexical parent, or nil for a root.
A DefineNode and BlockNode are detached roots: their Parent is nil even though they are written inside another template's source. The logical parents of a define or block body are the {{template}} and {{block}} call sites that invoke it, which are resolved by callers rather than recorded here.
func (*TemplateNode) Start ¶
func (t *TemplateNode) Start() lex.Pos
func (*TemplateNode) String ¶
func (t *TemplateNode) String() string
type TextNode ¶
type TextNode struct {
Text []byte // The text; may span newlines.
// Verbatim marks text that must render without HTML escaping in
// HTML mode. The parser sets it for preserved orphan end tags,
// which browsers ignore but stdlib html/template passes through.
Verbatim bool
// contains filtered or unexported fields
}
TextNode holds plain text.
func (TextNode) Parent ¶
func (n TextNode) Parent() Node
Parent returns the node's lexical parent, or nil for a root.
A DefineNode and BlockNode are detached roots: their Parent is nil even though they are written inside another template's source. The logical parents of a define or block body are the {{template}} and {{block}} call sites that invoke it, which are resolved by callers rather than recorded here.
type Tree ¶
type Tree struct {
Name string // name of the template represented by the tree.
ParseName string // name of the top-level template during parsing, for error messages.
Filepath string // absolute file path, if known.
Root *ListNode // top-level root of the tree.
// HTMLMode reports that this tree was parsed in HTML mode and must be
// executed through the HTML walker so contextual escaping is applied
// even when the root has no HTMLDocumentFragmentNode (for example, an
// extracted block or a tree composed via AddParseTree).
HTMLMode bool
// Diagnostics collects non-fatal structural findings recorded
// during parsing. See analysis.CheckStructure, which merges these
// with AST-walk findings.
Diagnostics Diagnostics
// RootTrimFirst and RootTrimLast carry a {{define ... -}}/{{- end}} or
// {{block ... -}}/{{- end}} node's own StartTrimRight/EndTrimLeft flags
// onto the standalone Tree Extract builds from its Body. A DefineNode
// or BlockNode's trim markers are otherwise only meaningful relative to
// siblings in the tree that contained it — walkHTMLList's trimFirst and
// trimLast parameters — but once extracted, the body has no such
// siblings; its own root-level whitespace is never trimmed unless the
// extracting node's flags are carried forward here and honored where
// the tree is executed as a root (executeHTMLList and the
// {{template}}-node HTML walker).
RootTrimFirst, RootTrimLast bool
// contains filtered or unexported fields
}
Tree is the representation of a single parsed template.
func ParseTree ¶
func ParseTree(fileName, templateName, text string, treeSet map[string]*Tree, options lex.Options) (*Tree, error)
ParseTree returns a map from template name to Tree, created by parsing the templates described in the argument string. The top-level template will be given the specified name. If an error is encountered, parsing stops and an empty map is returned with the error.
Use filepath.FromSlash on the fileName, ParseTree expects a slash separated filepath.
func (*Tree) PositionAt ¶
PositionAt computes the line and column (both 1-based) for a byte offset in the template text.
func (*Tree) RootStart ¶
RootStart returns the offset where text/template's parser started the tree's root list. Its lexer dropped the whitespace a {{define ... -}} or {{block ... -}} clause trims, so the list began at the first byte the template writes, or at the action after the trimmed space. This parser keeps that whitespace as text, trimmed at execution, and starts the list right after the clause.
type TreeFinder ¶
TreeFinder looks up associated templates by name.
type Trust ¶
type Trust int
Trust classifies values that should bypass contextual escaping in HTML-mode execution. The set mirrors the safe-content types from the standard html/template package.
const ( // TrustNone means the value gets default contextual escaping. TrustNone Trust = iota // TrustHTML marks a value as a known-safe HTML fragment. In body // context (text, not script/style), the value is rendered raw. TrustHTML // TrustURL marks a value as a known-safe URL. In URL attributes, // the safe-scheme filter is skipped. TrustURL // TrustJS marks a value as a known-safe JavaScript expression. In // script body context, JS-string escaping is skipped. TrustJS // TrustJSStr marks a value as known-safe content for inside a // quoted JavaScript string literal. JS-string escaping is skipped // in script string context. TrustJSStr // TrustCSS marks a value as known-safe CSS. In style body context, // CSS escaping is skipped. TrustCSS // TrustHTMLAttr marks a value as a known-safe HTML attribute value. // URL filtering and JS-event escaping are skipped. TrustHTMLAttr // TrustSrcset marks a value as a known-safe srcset attribute value. // Per-URL safe-scheme filtering is skipped. TrustSrcset )
type TrustFunc ¶
TrustFunc inspects a runtime value and reports its trust classification. A nil TrustFunc behaves like one that returns TrustNone.
type VariableNode ¶
type VariableNode struct {
Ident []string // Variable name and fields in lexical order.
// contains filtered or unexported fields
}
VariableNode holds a list of variable names, possibly with chained field accesses. The dollar sign is part of the (first) name.
func (*VariableNode) End ¶
func (v *VariableNode) End() lex.Pos
func (*VariableNode) Start ¶
func (v *VariableNode) Start() lex.Pos
func (*VariableNode) String ¶
func (v *VariableNode) String() string
type WithNode ¶
type WithNode struct {
BranchNode
}
WithNode represents a {{with}} action and its commands.
func (WithNode) Parent ¶
func (n WithNode) Parent() Node
Parent returns the node's lexical parent, or nil for a root.
A DefineNode and BlockNode are detached roots: their Parent is nil even though they are written inside another template's source. The logical parents of a define or block body are the {{template}} and {{block}} call sites that invoke it, which are resolved by callers rather than recorded here.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package lex provides the template and HTML lexer, source positions, and parse options used by the muxt template parser.
|
Package lex provides the template and HTML lexer, source positions, and parse options used by the muxt template parser. |
|
Package html provides muxt with an html/template-compatible, context-aware escaping template engine built on the position-tracking template parser.
|
Package html provides muxt with an html/template-compatible, context-aware escaping template engine built on the position-tracking template parser. |