Пакет parse
Обзор
Пакет parse строит деревья разбора для шаблонов, как определено в text/template и html/template. Клиенты должны использовать эти пакеты для построения шаблонов, а не этот, который предоставляет общие внутренние структуры данных, не предназначенные для общего использования.
Индекс
Файлы пакета
lex.go node.go parse.go
func IsEmptyTree
func IsEmptyTree(n Node) bool
IsEmptyTree проверяет, пусто ли это дерево (узел), содержащее только пробелы или комментарии.
func Parse
func Parse(name, text, leftDelim, rightDelim string, funcs ...map[string]any) (map[string]*Tree, error)
Parse возвращает карту от имени шаблона к Tree, созданную путем разбора шаблонов, описанных в строке аргумента. Шаблон верхнего уровня получит указанное имя. Если возникает ошибка, разбор останавливается, и возвращается пустая карта с ошибкой.
тип ActionNode
ActionNode хранит действие (что-то ограниченное разделителями). Действия управления имеют свои узлы; ActionNode представляет собой простые, такие как вычисления поля и скобки с конвейерами.
type ActionNode struct {
NodeType
Pos
Line int // The line number in the input. Deprecated: Kept for compatibility.
Pipe *PipeNode // The pipeline in the action.
// contains filtered or unexported fields
}
func (*ActionNode) Copy
func (a *ActionNode) Copy() Node
func (*ActionNode) String
func (a *ActionNode) String() string
тип BoolNode
BoolNode хранит булеву константу.
type BoolNode struct {
NodeType
Pos
True bool // The value of the boolean constant.
// contains filtered or unexported fields
}
func (*BoolNode) Copy
func (b *BoolNode) Copy() Node
func (*BoolNode) String
func (b *BoolNode) String() string
тип BranchNode
BranchNode — общее представление if, range и with.
type BranchNode struct {
NodeType
Pos
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).
// contains filtered or unexported fields
}
func (*BranchNode) Copy 1.4
func (b *BranchNode) Copy() Node
func (*BranchNode) String
func (b *BranchNode) String() string
тип BreakNode 1.18
BreakNode представляет собой действие {{break}}.
type BreakNode struct {
NodeType
Pos
Line int
// contains filtered or unexported fields
}
func (*BreakNode) Copy 1.18
func (b *BreakNode) Copy() Node
func (*BreakNode) String 1.18
func (b *BreakNode) String() string
тип ChainNode 1.1
ChainNode хранит термин, за которым следует цепочка обращений к полям (идентификатор, начинающийся с '.'). Имена могут быть связаны цепочкой ('.x.y'). Точки из каждого идентификатора опускаются.
type ChainNode struct {
NodeType
Pos
Node Node
Field []string // The identifiers in lexical order.
// contains filtered or unexported fields
}
func (*ChainNode) Add 1.1
func (c *ChainNode) Add(field string)
Add добавляет именованное поле (которое должно начинаться с точки) в конец цепочки.
func (*ChainNode) Copy 1.1
func (c *ChainNode) Copy() Node
func (*ChainNode) String 1.1
func (c *ChainNode) String() string
тип CommandNode
CommandNode хранит команду (конвейер внутри оцениваемого действия).
type CommandNode struct {
NodeType
Pos
Args []Node // Arguments in lexical order: Identifier, field, or constant.
// contains filtered or unexported fields
}
func (*CommandNode) Copy
func (c *CommandNode) Copy() Node
func (*CommandNode) String
func (c *CommandNode) String() string
тип CommentNode 1.16
CommentNode хранит комментарий.
type CommentNode struct {
NodeType
Pos
Text string // Comment text.
// contains filtered or unexported fields
}
func (*CommentNode) Copy 1.16
func (c *CommentNode) Copy() Node
func (*CommentNode) String 1.16
func (c *CommentNode) String() string
тип ContinueNode 1.18
ContinueNode представляет собой действие {{continue}}.
type ContinueNode struct {
NodeType
Pos
Line int
// contains filtered or unexported fields
}
func (*ContinueNode) Copy 1.18
func (c *ContinueNode) Copy() Node
func (*ContinueNode) String 1.18
func (c *ContinueNode) String() string
тип DotNode
DotNode хранит специальный идентификатор '.'.
type DotNode struct {
NodeType
Pos
// contains filtered or unexported fields
}
func (*DotNode) Copy
func (d *DotNode) Copy() Node
func (*DotNode) String
func (d *DotNode) String() string
func (*DotNode) Type
func (d *DotNode) Type() NodeType
тип FieldNode
FieldNode хранит поле (идентификатор, начинающийся с '.'). Имена могут быть связаны цепочкой ('.x.y'). Точка из каждого идентификатора опускается.
type FieldNode struct {
NodeType
Pos
Ident []string // The identifiers in lexical order.
// contains filtered or unexported fields
}
func (*FieldNode) Copy
func (f *FieldNode) Copy() Node
func (*FieldNode) String
func (f *FieldNode) String() string
тип IdentifierNode
IdentifierNode хранит идентификатор.
type IdentifierNode struct {
NodeType
Pos
Ident string // The identifier's name.
// contains filtered or unexported fields
}
func NewIdentifier
func NewIdentifier(ident string) *IdentifierNode
NewIdentifier возвращает новый IdentifierNode с заданным именем идентификатора.
func (*IdentifierNode) Copy
func (i *IdentifierNode) Copy() Node
func (*IdentifierNode) SetPos 1.1
func (i *IdentifierNode) SetPos(pos Pos) *IdentifierNode
SetPos устанавливает позицию. NewIdentifier — это публичный метод, поэтому его сигнатуру изменить нельзя. Используется для удобства цепочки вызовов. TODO: исправить когда-нибудь?
func (*IdentifierNode) SetTree 1.4
func (i *IdentifierNode) SetTree(t *Tree) *IdentifierNode
SetTree устанавливает родительское дерево для узла. NewIdentifier — это публичный метод, поэтому его сигнатуру изменить нельзя. Используется для удобства цепочки вызовов. TODO: исправить когда-нибудь?
func (*IdentifierNode) String
func (i *IdentifierNode) String() string
type IfNode
IfNode представляет собой действие {{if}} и его команды.
type IfNode struct {
BranchNode
}
func (*IfNode) Copy
func (i *IfNode) Copy() Node
type ListNode
ListNode хранит последовательность узлов.
type ListNode struct {
NodeType
Pos
Nodes []Node // The element nodes in lexical order.
// contains filtered or unexported fields
}
func (*ListNode) Copy
func (l *ListNode) Copy() Node
func (*ListNode) CopyList
func (l *ListNode) CopyList() *ListNode
func (*ListNode) String
func (l *ListNode) String() string
type Mode 1.16
Значение режима — это набор флагов (или 0). Режимы управляют поведением парсера.
type Mode uint
const (
ParseComments Mode = 1 << iota // parse comments and add them to AST
SkipFuncCheck // do not check that functions are defined
) type NilNode 1.1
NilNode хранит специальный идентификатор 'nil', представляющий неуказанную константу nil.
type NilNode struct {
NodeType
Pos
// contains filtered or unexported fields
}
func (*NilNode) Copy 1.1
func (n *NilNode) Copy() Node
func (*NilNode) String 1.1
func (n *NilNode) String() string
func (*NilNode) Type 1.1
func (n *NilNode) Type() NodeType
type Node
Node — это элемент в дереве разбора. Интерфейс тривиален. Интерфейс содержит неэкспортируемый метод, чтобы только типы, локальные для этого пакета, могли его реализовывать.
type Node interface {
Type() NodeType
String() string
// Copy does a deep copy of the Node and all its components.
// To avoid type assertions, some XxxNodes also have specialized
// CopyXxx methods that return *XxxNode.
Copy() Node
Position() Pos // byte position of start of node in full original input string
// contains filtered or unexported methods
} type NodeType
NodeType определяет тип узла дерева разбора.
type NodeType int
const (
NodeText NodeType = iota // Plain text.
NodeAction // A non-control action such as a field evaluation.
NodeBool // A boolean constant.
NodeChain // A sequence of field accesses.
NodeCommand // An element of a pipeline.
NodeDot // The cursor, dot.
NodeField // A field or method name.
NodeIdentifier // An identifier; always a function name.
NodeIf // An if action.
NodeList // A list of Nodes.
NodeNil // An untyped nil constant.
NodeNumber // A numerical constant.
NodePipe // A pipeline of commands.
NodeRange // A range action.
NodeString // A string constant.
NodeTemplate // A template invocation action.
NodeVariable // A $ variable.
NodeWith // A with action.
NodeComment // A comment.
NodeBreak // A break action.
NodeContinue // A continue action.
) func (NodeType) Type
func (t NodeType) Type() NodeType
Type возвращает себя и предоставляет простую реализацию по умолчанию для встраивания в узел. Встроено во все нетривиальные узлы.
type NumberNode
NumberNode хранит число: целое со знаком или без знака, число с плавающей точкой или комплексное число. Значение анализируется и хранится во всех типах, которые могут представлять значение. Это моделирует в небольшом количестве кода поведение идеальных констант Go.
type NumberNode struct {
NodeType
Pos
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
}
func (*NumberNode) Copy
func (n *NumberNode) Copy() Node
func (*NumberNode) String
func (n *NumberNode) String() string
type PipeNode
PipeNode хранит конвейер с необязательной декларацией
type PipeNode struct {
NodeType
Pos
Line int // The line number in the input. Deprecated: Kept for compatibility.
IsAssign bool // The variables are being assigned, not declared; added in Go 1.11
Decl []*VariableNode // Variables in lexical order.
Cmds []*CommandNode // The commands in lexical order.
// contains filtered or unexported fields
}
func (*PipeNode) Copy
func (p *PipeNode) Copy() Node
func (*PipeNode) CopyPipe
func (p *PipeNode) CopyPipe() *PipeNode
func (*PipeNode) String
func (p *PipeNode) String() string
type Pos 1.1
Pos представляет байтовую позицию в исходном тексте ввода, из которого был проанализирован этот шаблон.
type Pos int
func (Pos) Position 1.1
func (p Pos) Position() Pos
type RangeNode
RangeNode представляет собой действие {{range}} и его команды.
type RangeNode struct {
BranchNode
}
func (*RangeNode) Copy
func (r *RangeNode) Copy() Node
type StringNode
StringNode хранит строковую константу. Значение было "разцитировано".
type StringNode struct {
NodeType
Pos
Quoted string // The original text of the string, with quotes.
Text string // The string, after quote processing.
// contains filtered or unexported fields
}
func (*StringNode) Copy
func (s *StringNode) Copy() Node
func (*StringNode) String
func (s *StringNode) String() string
type TemplateNode
TemplateNode представляет собой действие {{template}}.
type TemplateNode struct {
NodeType
Pos
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.
// contains filtered or unexported fields
}
func (*TemplateNode) Copy
func (t *TemplateNode) Copy() Node
func (*TemplateNode) String
func (t *TemplateNode) String() string
type TextNode
TextNode хранит обычный текст.
type TextNode struct {
NodeType
Pos
Text []byte // The text; may span newlines.
// contains filtered or unexported fields
}
func (*TextNode) Copy
func (t *TextNode) Copy() Node
func (*TextNode) String
func (t *TextNode) String() string
type Tree
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; added in Go 1.1
Root *ListNode // top-level root of the tree.
Mode Mode // parsing mode; added in Go 1.16
// contains filtered or unexported fields
}
func New
func New(name string, funcs ...map[string]any) *Tree
New выделяет новое дерево разбора с заданным именем.
func (*Tree) Copy 1.2
func (t *Tree) Copy() *Tree
Copy возвращает копию Tree. Любое состояние разбора отбрасывается.
func (*Tree) ErrorContext 1.1
func (t *Tree) ErrorContext(n Node) (location, context string)
ErrorContext возвращает текстовое представление расположения узла в тексте входных данных. Приемник используется только тогда, когда узел не имеет указателя на дерево внутри, что может произойти в старом коде.
func (*Tree) Parse
func (t *Tree) Parse(text, leftDelim, rightDelim string, treeSet map[string]*Tree, funcs ...map[string]any) (tree *Tree, err error)
Parse анализирует строку определения шаблона для создания представления шаблона для выполнения. Если строка разделителя действия пуста, используется значение по умолчанию ("{{" или "}}"). Встроенные определения шаблонов добавляются в карту treeSet.
type VariableNode
VariableNode хранит список имен переменных, возможно, с цепочкой обращений к полям. Знак доллара входит в (первое) имя.
type VariableNode struct {
NodeType
Pos
Ident []string // Variable name and fields in lexical order.
// contains filtered or unexported fields
}
func (*VariableNode) Copy
func (v *VariableNode) Copy() Node
func (*VariableNode) String
func (v *VariableNode) String() string
type WithNode
WithNode представляет собой действие {{with}} и его команды.
type WithNode struct {
BranchNode
}
func (*WithNode) Copy
func (w *WithNode) Copy() Node
© Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
http://golang.org/pkg/text/template/parse/