Пакет 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, созданными путём разбора шаблонов, описанных в строке аргумента. Для шаблона верхнего уровня будет задано указанное имя. Если возникает ошибка, разбор прекращается, возвращается пустое отображение и ошибка.
type 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
type 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
type 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
type 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
type 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
type 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
type 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
type 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
type 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
type 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
type 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
Значение Mode представляет собой набор флагов (или 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 возвращает само значение и предоставляет простую реализацию по умолчанию для встраивания в Node. Встроен во все нетривиальные узлы Node.
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/