htt

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

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 22 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 htt parses Go templates into trees that keep source positions and HTML structure, and executes those trees.

The parser accepts the templates text/template and html/template accept. In HTML mode, elements, attributes and comments are nodes beside the actions, and each {{define}} and {{block}} stays where it was written. Package template puts html/template's API over the same engine.

Execution serves analysis, tests and coverage. Its contextual escaping is weaker than html/template's (see ExecuteTemplate), so its output must not be served to a browser.

The API carries no compatibility promise.

Parts of this module derive from the Go standard library; see NOTICE.txt.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AnnotateHTMLContexts

func AnnotateHTMLContexts(root Node)

AnnotateHTMLContexts sets HTMLContext on each ActionNode and TemplateNode under root from its place in the tree.

func DefinedTrees

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

DefinedTrees returns the trees a parse defined, by name, as a text/template set would hold them. root is the tree ParseTree returned and treeSet the set it filled. A define's tree comes from Extract and carries the diagnostics recorded in its body.

func EscapeJS

func EscapeJS(s string) string

EscapeJS escapes s for the inside of a JavaScript string literal.

func ExecuteDocument

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

ExecuteDocument executes the top-level tree of an HTML-mode parse and returns the document it builds, unrendered.

func ExecuteElement

func ExecuteElement(tree *Tree, elem *HTMLElementNode, data any, opts ...Option) (*html.Node, error)

ExecuteElement executes one element of tree and returns its node.

func ExecuteTemplate

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

ExecuteTemplate executes tree with data as dot and writes the output to w. A text tree is written as text/template writes it. A tree parsed in HTML mode is escaped by the contexts AnnotateHTMLContexts set on it, and as HTML text where it set none.

Execution is for analysis, tests and coverage. Its output must not be served: the escaping falls short of html/template's, in these places among others.

  • A style attribute's value is not filtered as CSS.
  • A URL attribute's value is checked for its scheme but is not percent-encoded.
  • A text tree called from an HTML tree is not escaped for the place it is called from.
Example
package main

import (
	"fmt"
	"os"

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

func main() {
	tree, err := htt.ParseTree("page.gohtml", "page", `<a href="{{.URL}}">{{.Title}}</a>`, nil, lex.NewOptions())
	if err != nil {
		fmt.Println(err)
		return
	}
	htt.AnnotateHTMLContexts(tree.Root)
	data := struct{ URL, Title string }{URL: "javascript:alert(1)", Title: "<Home>"}
	if err := htt.ExecuteTemplate(os.Stdout, tree, data); err != nil {
		fmt.Println(err)
	}
}
Output:
<a href="#ZgotmplZ">&lt;Home&gt;</a>

func Extract

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

Extract yields a tree, by name, for each {{define}} and {{block}} in src. It does not yield src itself or look inside a definition's body.

func HasImpliedEndTag

func HasImpliedEndTag(tag string) bool

HasImpliedEndTag reports whether the named element, in lower case, may leave out its end tag: the "generate implied end tags" set of WHATWG §13.2.6.3 with its "thoroughly" additions.

func IsEmptyTree

func IsEmptyTree(n Node) bool

IsEmptyTree reports whether n holds nothing but space and comments.

func IsFormattingElement

func IsFormattingElement(tag string) bool

IsFormattingElement reports whether the named element, in lower case, is a formatting element (WHATWG §13.2.4.2), which the adoption agency algorithm reopens when another element's end tag closes it.

func IsTrue

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

IsTrue reports whether val is true as {{if}} sees it, meaning not the zero of its type, and whether val has a meaningful truth value.

func Walk

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

Walk calls fn for each node of tree in source order, a parent before its children. It does not enter actions.

func WalkPath

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

WalkPath is Walk with the node's ancestors, outermost first. The path includes list and branch nodes. fn must not keep path, whose 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 AnnotateHTMLContexts; nil in non-HTML mode.

	TrimLeft  bool // {{- was used
	TrimRight bool // -}} was used
	// contains filtered or unexported fields
}

ActionNode holds an action that is not a control structure, such as a field evaluation.

func (*ActionNode) End

func (a *ActionNode) End() lex.Pos

func (ActionNode) Parent

func (n ActionNode) Parent() Node

Parent returns the node's lexical parent. It is nil for a root, and for a DefineNode or BlockNode, which root a template of their own.

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 is a {{block}} kept where it was written. Pipe evaluates to dot for the body.

func (*BlockNode) Call

func (b *BlockNode) Call() *TemplateNode

Call returns the {{template}} call a block stands for: the template named Name with Pipe as dot. It spans the block and is the same node each time.

func (*BlockNode) End

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

func (BlockNode) Parent

func (n BlockNode) Parent() Node

Parent returns the node's lexical parent. It is nil for a root, and for a DefineNode or BlockNode, which root a template of their own.

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 of an {{else if}} or {{else with}} chained onto b, or nil. A plain {{else}} that holds a nested branch is no chain.

func (*BranchNode) End

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

func (BranchNode) Parent

func (n BranchNode) Parent() Node

Parent returns the node's lexical parent. It is nil for a root, and for a DefineNode or BlockNode, which root a template of their own.

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. It is nil for a root, and for a DefineNode or BlockNode, which root a template of their own.

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 field accesses, as in (.X).y.z. The periods are dropped from Field.

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. It is nil for a root, and for a DefineNode or BlockNode, which root a template of their own.

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. It is nil for a root, and for a DefineNode or BlockNode, which root a template of their own.

func (*ContinueNode) Start

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

func (*ContinueNode) String

func (c *ContinueNode) String() string

type CoverBlock

type CoverBlock struct {
	ParseName              string
	StartLine, StartColumn int
	EndLine, EndColumn     int
	Count                  int64 // how many times the block has run
}

CoverBlock is one span of a template's source that a cover profile counts.

func (CoverBlock) String

func (b CoverBlock) String() string

String returns the block as a cover profile names it: name:line.column,line.column.

type CoverProfile

type CoverProfile struct {
	// contains filtered or unexported fields
}

CoverProfile collects which nodes of the executed trees ran. Pass one to an execution with WithCoverProfile, then call WriteTo. The counters live on the nodes, so a tree's counts span every execution of it.

Example
package main

import (
	"fmt"
	"io"
	"os"

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

func main() {
	tree, err := htt.ParseTree("page.gohtml", "page", `{{if .OK}}<p>yes</p>{{else}}<p>no</p>{{end}}`, nil, lex.NewOptions())
	if err != nil {
		fmt.Println(err)
		return
	}
	profile := new(htt.CoverProfile)
	data := struct{ OK bool }{OK: true}
	if err := htt.ExecuteTemplate(io.Discard, tree, data, htt.WithCoverProfile(profile)); err != nil {
		fmt.Println(err)
		return
	}
	if _, err := profile.WriteTo(os.Stdout); err != nil {
		fmt.Println(err)
	}
}
Output:
mode: set
page.gohtml:1.1,1.21 5 1
page.gohtml:1.21,1.38 5 0
page.gohtml:1.38,1.45 1 1

func (*CoverProfile) AddTree

func (cp *CoverProfile) AddTree(tree *Tree)

AddTree adds tree to the profile. Execution adds the trees it runs.

func (*CoverProfile) WriteNewlyCovered

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

WriteNewlyCovered writes a line for each block that has run and is not in written, then adds those blocks to written. The lines have WriteTo's format, with no mode line. A block is keyed by parse name and position, so a reparsed tree writes nothing twice. If the write fails, written is left as it was.

func (*CoverProfile) WriteTo

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

WriteTo writes the profile in the format of go tool cover.

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 is a {{define}} kept where it was written. text/template moves a define into its own tree while parsing; Extract does that afterward.

func (*DefineNode) End

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

func (DefineNode) Parent

func (n DefineNode) Parent() Node

Parent returns the node's lexical parent. It is nil for a root, and for a DefineNode or BlockNode, which root a template of their own.

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 finding that does not stop the parse: a place where a browser would build a tree other than the one the source spells.

func (Diagnostic) String

func (d Diagnostic) String() string

String formats d with its severity and byte offset.

type DiagnosticCode

type DiagnosticCode string

DiagnosticCode names a class of finding. Codes are stable.

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

The codes for HTML structure. The parser reports DiagOrphanEndTag and DiagMisnestedTag; the others are for analyses built on the tree. An analysis of anything else declares its own codes.

type Diagnostics

type Diagnostics []Diagnostic

Diagnostics is a list of findings.

func (Diagnostics) SortByPos

func (ds Diagnostics) SortByPos()

SortByPos sorts ds by position, keeping the order of equals.

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

func (FindTreeFunc) FindTree

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

FindTree calls f.

type FuncMap

type FuncMap map[string]any

FuncMap maps names to functions. Each function returns one value, or a value and 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 is an HTML attribute. Key and Value interleave text with actions.

func (*HTMLAttributeNode) End

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

func (HTMLAttributeNode) Parent

func (n HTMLAttributeNode) Parent() Node

Parent returns the node's lexical parent. It is nil for a root, and for a DefineNode or BlockNode, which root a template of their own.

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 is an HTML comment. Children interleaves its text with the actions written in it.

func (*HTMLCommentNode) End

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

func (HTMLCommentNode) Parent

func (n HTMLCommentNode) Parent() Node

Parent returns the node's lexical parent. It is nil for a root, and for a DefineNode or BlockNode, which root a template of their own.

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 in script content: "expr", "str" in a quoted
	// string, "tpl" in a template literal, "regex" or "comment". A ${...}
	// in a template literal is "expr".
	JSContext string
}

HTMLContext is the escaping context of an action.

type HTMLDoctypeNode

type HTMLDoctypeNode struct {
	Text string // The raw DOCTYPE text, e.g. "<!DOCTYPE html>".
	// contains filtered or unexported fields
}

HTMLDoctypeNode is a 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. It is nil for a root, and for a DefineNode or BlockNode, which root a template of their own.

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 holds the top-level nodes of a tree parsed in HTML mode. It imposes no well-formedness.

func (*HTMLDocumentFragmentNode) End

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

func (HTMLDocumentFragmentNode) Parent

func (n HTMLDocumentFragmentNode) Parent() Node

Parent returns the node's lexical parent. It is nil for a root, and for a DefineNode or BlockNode, which root a template of their own.

func (*HTMLDocumentFragmentNode) Start

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

func (*HTMLDocumentFragmentNode) String

func (n *HTMLDocumentFragmentNode) String() string

type HTMLElementNode

type HTMLElementNode struct {
	TagName     string  // The tag name as written.
	Attr        []Node  // HTMLAttributeNode values, and the actions and control structures among them.
	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 is an HTML element. A tag with an action in its name is not an element: the parser reads it as text.

func (*HTMLElementNode) End

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

func (HTMLElementNode) Parent

func (n HTMLElementNode) Parent() Node

Parent returns the node's lexical parent. It is nil for a root, and for a DefineNode or BlockNode, which root a template of their own.

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. It is nil for a root, and for a DefineNode or BlockNode, which root a template of their own.

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. It is nil for a root, and for a DefineNode or BlockNode, which root a template of their own.

func (ListNode) Start

func (l ListNode) Start() lex.Pos

func (ListNode) String

func (l ListNode) String() string

type MissingKeyMode

type MissingKeyMode int

MissingKeyMode says what a map lookup with a missing key evaluates to. A missing struct field is an error in every mode.

const (
	// MissingKeyInvalid is the default: no value, printed as "<no value>".
	MissingKeyInvalid MissingKeyMode = iota
	// MissingKeyZero is the zero value of the map's element type.
	MissingKeyZero
	// MissingKeyError stops execution with 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 of the parse tree. Only this package implements 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 an execution.

func WithCoverProfile

func WithCoverProfile(cp *CoverProfile) Option

WithCoverProfile records in cp which nodes run.

func WithFinder

func WithFinder(finder TreeFinder) Option

WithFinder sets how {{template}} calls find their trees. Without one, every call fails.

func WithFuncs

func WithFuncs(funcs FuncMap) Option

WithFuncs sets the functions templates may call besides the builtins.

func WithMissingKey

func WithMissingKey(mode MissingKeyMode) Option

WithMissingKey sets the MissingKeyMode.

func WithTrust

func WithTrust(f TrustFunc) Option

WithTrust sets the function that says which values skip contextual escaping in HTML mode.

type ParseError

type ParseError struct {
	// contains filtered or unexported fields
}

ParseError is a parse failure with its place in the template text. Error keeps text/template's "template: name:line: message" form.

func (*ParseError) EndPosition

func (e *ParseError) EndPosition() token.Position

EndPosition returns the position just past the failing token.

func (*ParseError) Error

func (e *ParseError) Error() string

func (*ParseError) Position

func (e *ParseError) Position() token.Position

Position returns where the failing token starts.

func (*ParseError) Unwrap

func (e *ParseError) Unwrap() error

Unwrap returns the cause, whose message has no 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 the commands text/template evaluates for p. A first command that is nothing but a parenthesized pipeline declaring no variables gives way to that pipeline's commands, so {{if (and .A .B)}} yields the commands of {{if and .A .B}}. Parentheses anywhere else stay. The result may be 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 // the text of the node, when the position is a node's
}

Position is a 1-based line and column in a template's source.

func (Position) String

func (p Position) String() string

String formats p as name:line:column.

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. It is nil for a root, and for a DefineNode or BlockNode, which root a template of their own.

type Severity

type Severity int

Severity ranks a Diagnostic.

const (
	SeverityWarning Severity = iota
	SeverityError
)

The severities.

func (Severity) String

func (s Severity) String() string

String returns "warning" or "error".

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
}

Template is a set of named trees parsed together, and one tree in it. Signature is the caller's representation of a function; the set only records which names are registered.

func New

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

New returns a set that parses in HTML mode, as html/template does.

func NewText

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

NewText returns a set that parses as text/template does, with no HTML structure.

func (*Template[S]) AddParseTree

func (t *Template[S]) AddParseTree(name string, tree *Tree) (*Template[S], error)

AddParseTree adds tree to the set under name and returns its template. An empty tree does not replace one already there.

func (*Template[S]) Delimiters

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

Delimiters sets the action delimiters for later calls to Parse. It returns t.

func (*Template[S]) FindTree

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

FindTree implements TreeFinder.

func (*Template[S]) Functions

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

Functions registers functions by name. It returns t.

func (*Template[S]) IsText

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

IsText reports whether t came from NewText.

func (*Template[S]) Lookup

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

Lookup returns the template named name, or nil.

func (*Template[S]) Name

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

Name returns the template's name.

func (*Template[S]) Names

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

Names returns the sorted names of the templates in the set.

func (*Template[S]) Option

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

Option sets options as text/template's Option does. The only option is missingkey.

func (*Template[S]) Parse

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

Parse parses text as the body of t and adds the templates it defines to the set.

func (*Template[S]) ParseOptions

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

ParseOptions returns the lexer options Parse uses.

func (*Template[S]) SkipFuncCheck

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

SkipFuncCheck makes Parse accept calls of functions that are not registered. It returns t.

func (*Template[S]) Tree

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

Tree returns the template's tree, which is nil until it is parsed.

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. It is nil for a root, and for a DefineNode or BlockNode, which root a template of their own.

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. It is nil for a root, and for a DefineNode or BlockNode, which root a template of their own.

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 says the tree executes with contextual escaping, whatever
	// its root holds.
	HTMLMode bool
	// Diagnostics holds the structural findings recorded while parsing.
	Diagnostics Diagnostics
	// RootTrimFirst and RootTrimLast are the trim markers of the {{define}}
	// or {{block}} whose body is this tree's root: -}} on the opener and
	// {{- on the end.
	RootTrimFirst, RootTrimLast bool
	// contains filtered or unexported fields
}

Tree is the representation of a single parsed template.

Example (Diagnostics)
package main

import (
	"fmt"

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

func main() {
	tree, err := htt.ParseTree("page.gohtml", "page", `<p>one</b> two</p>`, nil, lex.NewOptions())
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, d := range tree.Diagnostics {
		fmt.Println(tree.PositionAt(d.Pos), d.Code, d.Message)
	}
}
Output:
page.gohtml:1:7 orphan-end-tag unmatched </b> is ignored by browsers

func ParseTree

func ParseTree(fileName, templateName, text string, treeSet map[string]*Tree, options lex.Options) (*Tree, error)

ParseTree parses text and returns the tree of the template named templateName. It adds that tree, and one for each {{define}} and {{block}} in text, to treeSet, which may be nil. fileName is a slash-separated path used in positions and error messages.

Example
package main

import (
	"fmt"

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

func main() {
	const page = `<ul>{{range .Items}}<li class="item">{{.}}</li>{{end}}</ul>`
	tree, err := htt.ParseTree("page.gohtml", "page", page, nil, lex.NewOptions())
	if err != nil {
		fmt.Println(err)
		return
	}
	htt.Walk(tree, func(t *htt.Tree, n htt.Node) {
		switch n := n.(type) {
		case *htt.HTMLElementNode:
			fmt.Printf("%s <%s>\n", t.Position(n), n.TagName)
		case *htt.RangeNode:
			fmt.Printf("%s range %s\n", t.Position(n), n.Pipe.Commands[0])
		case *htt.ActionNode:
			fmt.Printf("%s %s\n", t.Position(n), n)
		}
	})
}
Output:
page.gohtml:1:1 <ul>
page.gohtml:1:5 range .Items
page.gohtml:1:21 <li>
page.gohtml:1:38 {{.}}

func (*Tree) CoverBlocks

func (t *Tree) CoverBlocks() []CoverBlock

CoverBlocks returns the tree's coverable blocks in source order, one per coverable node, as WriteNewlyCovered writes them. A tree with no parse name has none.

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

Position returns the position of n's start, with n's source text.

func (*Tree) PositionAt

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

PositionAt returns the line and column of a byte offset in the source. An offset outside the source counts as its nearer end.

func (*Tree) RootStart

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

RootStart returns the offset at which text/template would start this tree's root list. The two differ after {{define ... -}} and {{block ... -}}: text/template drops the trimmed space while lexing, and this parser keeps it as text.

func (*Tree) Source

func (t *Tree) Source() string

Source returns the whole text the tree was parsed from, which may define other templates too.

type TreeFinder

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

TreeFinder finds the tree a {{template}} call names.

type Trust

type Trust int

Trust says which contextual escaping a value skips in HTML mode. The kinds match html/template's safe-content types.

const (
	// TrustNone escapes the value for its context.
	TrustNone Trust = iota
	// TrustHTML is an HTML fragment, written as it is in element content.
	TrustHTML
	// TrustURL is a URL, not filtered by scheme.
	TrustURL
	// TrustJS is a JavaScript expression.
	TrustJS
	// TrustJSStr is text for the inside of a JavaScript string literal.
	TrustJSStr
	// TrustCSS is CSS, written as it is in a style element.
	TrustCSS
	// TrustHTMLAttr is an attribute value that skips every attribute
	// filter, or a name where an attribute is written.
	TrustHTMLAttr
	// TrustSrcset is a srcset value, not filtered by scheme.
	TrustSrcset
)

type TrustFunc

type TrustFunc func(reflect.Value) Trust

TrustFunc reports the Trust of a value. A nil TrustFunc trusts nothing.

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. It is nil for a root, and for a DefineNode or BlockNode, which root a template of their own.

Directories

Path Synopsis
Package lex is the lexer for package htt.
Package lex is the lexer for package htt.
Package template puts html/template's API over package htt, so that code written for html/template can run on trees that keep positions and count coverage.
Package template puts html/template's API over package htt, so that code written for html/template can run on trees that keep positions and count coverage.

Jump to

Keyboard shortcuts

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