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 ¶
- func AnnotateHTMLContexts(root Node)
- func DefinedTrees(root *Tree, treeSet map[string]*Tree) map[string]*Tree
- func EscapeJS(s string) string
- func ExecuteDocument(tree *Tree, data any, opts ...Option) (*html.Node, error)
- func ExecuteElement(tree *Tree, elem *HTMLElementNode, data any, opts ...Option) (*html.Node, error)
- func ExecuteTemplate(w io.Writer, tree *Tree, data any, opts ...Option) error
- func Extract(src *Tree) iter.Seq2[string, *Tree]
- func HasImpliedEndTag(tag string) bool
- func IsEmptyTree(n Node) bool
- func IsFormattingElement(tag string) bool
- func IsTrue(val any) (truth, ok bool)
- func Walk(tree *Tree, fn func(*Tree, Node))
- func WalkPath(tree *Tree, fn func(t *Tree, path []Node, n Node))
- type ActionNode
- type BlockNode
- type BoolNode
- type BranchNode
- type BreakNode
- type ChainNode
- type CommandNode
- type CommentNode
- type ContinueNode
- type CoverBlock
- type CoverProfile
- type DefineNode
- type Diagnostic
- type DiagnosticCode
- type Diagnostics
- type DotNode
- type ExecError
- type FieldNode
- type FindTreeFunc
- type FuncMap
- type HTMLAttributeNode
- type HTMLCommentNode
- type HTMLContext
- type HTMLDoctypeNode
- type HTMLDocumentFragmentNode
- type HTMLElementNode
- type IdentifierNode
- type IfNode
- type ListNode
- type MissingKeyMode
- type NilNode
- type Node
- type NumberNode
- type Option
- type ParseError
- type PipeNode
- type Position
- type RangeNode
- type Severity
- type StringNode
- type Template
- func (t *Template[S]) AddParseTree(name string, tree *Tree) (*Template[S], error)
- func (t *Template[S]) Delimiters(left, right string) *Template[S]
- func (t *Template[S]) FindTree(name string) (*Tree, bool)
- func (t *Template[S]) Functions(functions map[string]S) *Template[S]
- func (t *Template[S]) IsText() bool
- func (t *Template[S]) Lookup(name string) *Template[S]
- func (t *Template[S]) Name() string
- func (t *Template[S]) Names() []string
- func (t *Template[S]) Option(opt ...string) (*Template[S], error)
- func (t *Template[S]) Parse(text string) (*Template[S], error)
- func (t *Template[S]) ParseOptions() lex.Options
- func (t *Template[S]) SkipFuncCheck() *Template[S]
- func (t *Template[S]) Tree() *Tree
- type TemplateNode
- type TextNode
- type Tree
- type TreeFinder
- type Trust
- type TrustFunc
- type VariableNode
- type WithNode
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 ¶
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 ExecuteDocument ¶
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 ¶
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"><Home></a>
func Extract ¶
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 ¶
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 ¶
IsEmptyTree reports whether n holds nothing but space and comments.
func IsFormattingElement ¶
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 ¶
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.
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.
type BoolNode ¶
type BoolNode struct {
True bool // The value of the boolean constant.
// contains filtered or unexported fields
}
BoolNode holds a boolean constant.
type BranchNode ¶
type BranchNode struct {
Line int // The line number in the input. Deprecated: Kept for compatibility.
Pipe *PipeNode // The pipeline to be evaluated.
List *ListNode // What to execute if the value is non-empty.
ElseList *ListNode // What to execute if the value is empty (nil if absent).
StartTrimLeft bool // {{- on opener
StartTrimRight bool // -}} on opener
ElseTrimLeft bool // {{- on else
ElseTrimRight bool // -}} on else
EndTrimLeft bool // {{- on end
EndTrimRight bool // -}} on end
// contains filtered or unexported fields
}
BranchNode is the common representation of if, range, and with.
func (*BranchNode) ElseChain ¶
func (b *BranchNode) ElseChain() *BranchNode
ElseChain returns the branch 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.
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.
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 ¶
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.
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 '.'.
type ExecError ¶
ExecError is the custom error type returned when Execute fails. It provides the name of the template in which the error occurred.
type FieldNode ¶
type FieldNode struct {
Ident []string // The identifiers in lexical order.
// contains filtered or unexported fields
}
FieldNode holds a field (identifier starting with '.'). The names may be chained ('.x.y'). The period is dropped from each ident.
type FindTreeFunc ¶
FindTreeFunc adapts a function to TreeFinder.
type FuncMap ¶
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.
type ListNode ¶
type ListNode struct {
Nodes []Node // The element nodes in lexical order.
// contains filtered or unexported fields
}
ListNode holds a sequence of nodes.
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.
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 WithMissingKey ¶
func WithMissingKey(mode MissingKeyMode) Option
WithMissingKey sets the MissingKeyMode.
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) 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.
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.
type RangeNode ¶
type RangeNode struct {
BranchNode
}
RangeNode represents a {{range}} action and its commands.
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 (*Template[S]) AddParseTree ¶
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 ¶
Delimiters sets the action delimiters for later calls to Parse. It returns t.
func (*Template[S]) Option ¶
Option sets options as text/template's Option does. The only option is missingkey.
func (*Template[S]) Parse ¶
Parse parses text as the body of t and adds the templates it defines to the set.
func (*Template[S]) ParseOptions ¶
ParseOptions returns the lexer options Parse uses.
func (*Template[S]) SkipFuncCheck ¶
SkipFuncCheck makes Parse accept calls of functions that are not registered. It returns t.
type TemplateNode ¶
type TemplateNode struct {
Line int // The line number in the input. Deprecated: Kept for compatibility.
Name string // The name of the template (unquoted).
Pipe *PipeNode // The command to evaluate as dot for the template.
HTMLContext *HTMLContext // Set by AnnotateHTMLContexts; nil in non-HTML mode.
TrimLeft bool // {{- was used
TrimRight bool // -}} was used
// contains filtered or unexported fields
}
TemplateNode represents a {{template}} action.
func (*TemplateNode) End ¶
func (t *TemplateNode) End() lex.Pos
func (TemplateNode) Parent ¶
func (n TemplateNode) Parent() Node
Parent returns the node's lexical parent. 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.
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) PositionAt ¶
PositionAt returns the line and column of a byte offset in the source. An offset outside the source counts as its nearer end.
type TreeFinder ¶
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 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
Source Files
¶
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. |