htt

package module
v0.0.0-dev.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 20 Imported by: 0

README

htt

htt parses Go templates into trees that keep source positions and HTML structure, and executes those trees. It accepts the templates text/template and html/template accept.

It was factored out of muxt, which uses it to type check templates, format them, and record which template nodes a package's tests reach.

Status: do not serve its output yet

Render pages for a browser with the standard library's html/template. htt runs templates so that tests and tools can see what a template produces and which parts of it ran. Its contextual escaping is not yet equivalent to html/template's. The documentation of ExecuteTemplate lists the known differences, for example:

  • An action in attribute-name position, such as <div {{.Name}}="x">, is written as escaped text instead of a tag with a filtered attribute name.
  • A text template called from an HTML template runs without the caller's escaping context.
  • The value of a style or srcdoc attribute is not escaped for the CSS or HTML document it holds.

The aim is to close every difference and make htt/template a package you can serve from. Until then, treat its output as test data.

The API carries no compatibility promise; any release may change it.

Packages

Import path Provides
github.com/typelate/htt The parser, the tree (actions, HTML elements, attributes and comments as nodes with positions), and the execution engine.
github.com/typelate/htt/template The API of html/template over that engine.
github.com/typelate/htt/lex The lexer both use.
go get github.com/typelate/htt

Execute a template

htt/template has the names html/template has:

package main

import (
	"os"

	"github.com/typelate/htt/template"
)

func main() {
	t := template.Must(template.New("greeting.gohtml").Parse(`<p>Hello, {{.}}!</p>` + "\n"))
	if err := t.Execute(os.Stdout, "<World>"); err != nil {
		panic(err)
	}
}
<p>Hello, &lt;World&gt;!</p>

Read a template's structure

ParseTree returns a tree in which HTML elements are nodes beside the actions, each with its position in the source:

package main

import (
	"fmt"

	"github.com/typelate/htt"
	"github.com/typelate/htt/lex"
)

func main() {
	const src = "<ul>\n{{range .}}<li>{{.}}</li>{{end}}\n</ul>\n"
	tree, err := htt.ParseTree("list.gohtml", "list.gohtml", src, map[string]*htt.Tree{}, lex.NewOptions())
	if err != nil {
		panic(err)
	}
	htt.Walk(tree, func(t *htt.Tree, n htt.Node) {
		if el, ok := n.(*htt.HTMLElementNode); ok {
			p := t.Position(n)
			fmt.Printf("%s:%d:%d <%s>\n", p.ParseName, p.Line, p.Column, el.TagName)
		}
	})
}
list.gohtml:1:1 <ul>
list.gohtml:2:12 <li>

Template coverage

When the environment variable MUXT_TEMPLATE_COVER names a directory as the process starts, each execution through htt/template appends the template blocks it reaches to <dir>/<pid>.cov, in the format of a Go cover profile. muxt test-template-mutations sets it for its coverage pre-pass. Unset, nothing is written.

License

MIT; see LICENSE.md. Parts derive from the Go standard library's text/template and html/template, which carry Go's BSD-style license.

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

Constants

This section is empty.

Variables

View Source
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).

View Source
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

func DefinedTrees(root *Tree, treeSet map[string]*Tree) map[string]*Tree

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 EscapeCSS

func EscapeCSS(s string) string

EscapeCSS is the exported form of escapeCSSText for testing.

func EscapeJS

func EscapeJS(s string) string

EscapeJS is the exported form of escapeJS for testing.

func ExecuteDocument

func ExecuteDocument(tree *Tree, data any, opts ...Option) (*html.Node, error)

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

func ExecuteTemplate(w io.Writer, tree *Tree, data any, opts ...Option) error

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 (&lt;div ...&gt;) 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

func Extract(src *Tree) iter.Seq2[string, *Tree]

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

func FilterSrcset(s string) string

FilterSrcset is the exported form of filterSrcset for testing.

func FilterURL

func FilterURL(s string) string

FilterURL is the exported form of filterURL for testing.

func IsEmptyTree

func IsEmptyTree(n Node) bool

IsEmptyTree reports whether this tree (node) is empty of everything but space or comments.

func IsJSEventAttr

func IsJSEventAttr(attr string) bool

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

func IsRawTextElement(tag string) bool

IsRawTextElement reports whether the named element holds raw text whose contents are not HTML-escaped. Exported for tooling such as the LSP.

func IsTrue

func IsTrue(val any) (truth, ok bool)

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

func IsURLAttr(attr string) bool

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

func IsVoidElement(tag string) bool

IsVoidElement reports whether the named element is a void element (no closing tag). Exported for tooling such as the LSP.

func Walk

func Walk(tree *Tree, fn func(*Tree, Node))

Walk traverses the tree in source order, pre-order, calling fn for each node. It is a thin wrapper over WalkPath.

func WalkPath

func WalkPath(tree *Tree, fn func(t *Tree, path []Node, n Node))

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) End

func (b *BlockNode) End() lex.Pos

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.

func (*BlockNode) Start

func (b *BlockNode) Start() lex.Pos

func (*BlockNode) String

func (b *BlockNode) String() string

type BoolNode

type BoolNode struct {
	True bool // The value of the boolean constant.
	// contains filtered or unexported fields
}

BoolNode holds a boolean constant.

func (*BoolNode) End

func (b *BoolNode) End() lex.Pos

func (*BoolNode) Start

func (b *BoolNode) Start() lex.Pos

func (*BoolNode) String

func (b *BoolNode) String() string

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) End

func (b *BreakNode) End() lex.Pos

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.

func (*BreakNode) Start

func (b *BreakNode) Start() lex.Pos

func (*BreakNode) String

func (b *BreakNode) String() string

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.

func (*ChainNode) Add

func (c *ChainNode) Add(field string)

Add adds the named field (which should start with a period) to the end of the chain.

func (*ChainNode) End

func (c *ChainNode) End() lex.Pos

func (*ChainNode) Start

func (c *ChainNode) Start() lex.Pos

func (*ChainNode) String

func (c *ChainNode) String() string

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

func (cp *CoverProfile) WriteNewlyCovered(w io.Writer, written map[string]struct{}) (int64, error)

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.

func (*CoverProfile) WriteTo

func (cp *CoverProfile) WriteTo(w io.Writer) (int64, error)

WriteTo writes the coverage profile in the standard Go coverage format. It walks each registered tree's AST, reading counters from nodes.

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 '.'.

func (*DotNode) End

func (d *DotNode) End() lex.Pos

func (*DotNode) Start

func (d *DotNode) Start() lex.Pos

func (*DotNode) String

func (d *DotNode) String() string

type ExecError

type ExecError struct {
	Name string
	Err  error
}

ExecError is the custom error type returned when Execute fails. It provides the name of the template in which the error occurred.

func (ExecError) Error

func (e ExecError) Error() string

func (ExecError) Unwrap

func (e ExecError) Unwrap() error

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.

func (*FieldNode) End

func (f *FieldNode) End() lex.Pos

func (*FieldNode) Start

func (f *FieldNode) Start() lex.Pos

func (*FieldNode) String

func (f *FieldNode) String() string

type FindTreeFunc

type FindTreeFunc func(name string) (*Tree, bool)

FindTreeFunc adapts a function to the TreeFinder interface.

func (FindTreeFunc) FindTree

func (f FindTreeFunc) FindTree(name string) (*Tree, bool)

type FuncMap

type FuncMap map[string]any

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) End

func (l ListNode) End() lex.Pos

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.

func (ListNode) Start

func (l ListNode) Start() lex.Pos

func (ListNode) String

func (l ListNode) String() string

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.

func (*NilNode) End

func (n *NilNode) End() lex.Pos

func (*NilNode) Start

func (n *NilNode) Start() lex.Pos

func (*NilNode) String

func (n *NilNode) String() string

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 WithFuncs

func WithFuncs(funcs FuncMap) Option

WithFuncs provides custom template functions.

func WithMissingKey

func WithMissingKey(mode MissingKeyMode) Option

WithMissingKey sets the behavior for missing map keys and struct fields.

func WithTrust

func WithTrust(f TrustFunc) Option

WithTrust registers a TrustFunc used to detect safe-content types so they bypass the relevant contextual escaping in HTML mode.

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) End

func (p *PipeNode) End() lex.Pos

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.

func (*PipeNode) Start

func (p *PipeNode) Start() lex.Pos

func (*PipeNode) String

func (p *PipeNode) String() string

type Position

type Position struct {
	ParseName    string
	Line, Column int
	Source       string
}

func (Position) String

func (p Position) String() string

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 Severity

type Severity int

Severity indicates how a structural diagnostic should be treated.

const (
	SeverityWarning Severity = iota
	SeverityError
)

func (Severity) String

func (s Severity) String() string

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

func New[Signature any](name string) *Template[Signature]

New returns a template set that parses as html/template does: its trees hold HTML structure and are executed in HTML mode.

func NewText

func NewText[Signature any](name string) *Template[Signature]

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 (t *Template[S]) AddParseTree(name string, tree *Tree) (*Template[S], error)

func (*Template[S]) Delimiters

func (t *Template[S]) Delimiters(left, right string) *Template[S]

func (*Template[S]) FindTree

func (t *Template[S]) FindTree(name string) (*Tree, bool)

func (*Template[S]) Functions

func (t *Template[S]) Functions(functions map[string]S) *Template[S]

func (*Template[S]) IsText

func (t *Template[S]) IsText() bool

IsText reports whether the set parses as text/template does (NewText).

func (*Template[S]) Lookup

func (t *Template[S]) Lookup(name string) *Template[S]

func (*Template[S]) Name

func (t *Template[S]) Name() string

func (*Template[S]) Names

func (t *Template[S]) Names() []string

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]) Option

func (t *Template[S]) Option(opt ...string) (*Template[S], error)

func (*Template[S]) Parse

func (t *Template[S]) Parse(text string) (*Template[S], error)

func (*Template[S]) ParseOptions

func (t *Template[S]) ParseOptions() lex.Options

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

func (t *Template[S]) SkipFuncCheck() *Template[S]

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.

func (*Template[S]) Tree

func (t *Template[S]) Tree() *Tree

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) End

func (t *TextNode) End() lex.Pos

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.

func (*TextNode) Start

func (t *TextNode) Start() lex.Pos

func (*TextNode) String

func (t *TextNode) String() string

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) Delims

func (t *Tree) Delims() (left, right string)

Delims returns the action delimiters the tree was parsed with.

func (*Tree) Position

func (t *Tree) Position(n Node) Position

func (*Tree) PositionAt

func (t *Tree) PositionAt(pos lex.Pos) Position

PositionAt computes the line and column (both 1-based) for a byte offset in the template text.

func (*Tree) RootStart

func (t *Tree) RootStart() lex.Pos

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.

func (*Tree) Source

func (t *Tree) Source() string

Source returns the text the tree was parsed from: the whole file or string, with the text of the other templates it defines.

type TreeFinder

type TreeFinder interface {
	FindTree(name string) (*Tree, bool)
}

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

type TrustFunc func(reflect.Value) Trust

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.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL