Documentation
¶
Index ¶
- Variables
- func CreateBoolMap(arr []string) map[string]bool
- func CreateComponent(node *Node, attrs *Attributes, t *Compiler)
- func CreateNodeIdentifier(sequence *Sequence) func(*Node) string
- func HashMD5(text string) string
- func HashSha512Base64(content []byte) string
- func HashXXH64(content []byte) string
- func HashXXH64Hex(text string) string
- func HtmlEscape(s string) string
- func NormalizeName(name string) string
- func TestCompile(t *testing.T, template string, static []string, globalDirectives *Directives) (*Compiled, *Compiler)
- func TestRender(t *testing.T, compiled *Compiled, values map[string]interface{}, ...) (*Rendered, *Scope)
- func TestTemplate(t *testing.T, template string, values map[string]interface{}, expected string, ...) (*Rendered, *Scope)
- func TestUnindentedTemplate(template string) string
- type Attribute
- type Attributes
- func (a *Attributes) AddClass(value string)
- func (a *Attributes) Clone() *Attributes
- func (a *Attributes) Get(name string) (value string)
- func (a *Attributes) GetAttribute(name string) *Attribute
- func (a *Attributes) GetOrDefault(name string, dfault string) (value string)
- func (a *Attributes) HasClass(value string) bool
- func (a *Attributes) Remove(attr *Attribute)
- func (a *Attributes) RemoveClass(value string)
- func (a *Attributes) Render() *Rendered
- func (a *Attributes) Set(key string, value string)
- type Compiled
- type Compiler
- func (c *Compiler) Compile(template string, filepath string) (*Compiled, error)
- func (c *Compiler) NextHash() string
- func (c *Compiler) RegisterAsset(asset *cmn.Asset)
- func (c *Compiler) RegisterAssetJsContent(content string) *cmn.Asset
- func (c *Compiler) RegisterAssetJsFilepath(filepath string) (*cmn.Asset, error)
- func (c *Compiler) RegisterAssetJsURL(src string) (*cmn.Asset, error)
- func (c *Compiler) SafeRemove(node *Node)
- type Component
- type ComponentFunc
- type Context
- type Directive
- type DirectiveCompileFunc
- type DirectiveControllerFunc
- type DirectiveLeaveFunc
- type DirectiveLeaveInfo
- type DirectiveMethods
- type DirectiveProcessFunc
- type DirectiveProcessInfo
- type DirectiveRestrict
- type Directives
- type DirectivesByPriority
- type Dynamic
- type DynamicCompiled
- type DynamicDirectives
- type DynamicFunc
- type DynamicInterpolate
- type DynamicInterpolateEscaped
- type Expression
- type Live
- type Node
- func (n *Node) AppendChild(c *Node)
- func (n *Node) DebugTag() string
- func (n *Node) ExtractChildren() *Node
- func (n *Node) GetChildNodes() []*Node
- func (n *Node) Remove()
- func (n *Node) RemoveChild(c *Node)
- func (n *Node) Render() (string, error)
- func (n *Node) ReplaceByText() *Node
- func (n *Node) Transverse(callback func(node *Node) (stop bool))
- type NodeType
- type RegexMatch
- type Rendered
- type Scope
- type Sequence
- type StringSet
- type TemplateSystem
- func (s *TemplateSystem) Compile(filepath string) (*Compiled, *Context, error)
- func (s *TemplateSystem) Load(filepath string) (string, error)
- func (s *TemplateSystem) NewScope() *Scope
- func (s *TemplateSystem) Register(directives ...*Directive)
- func (s *TemplateSystem) RegisterAsset(asset *cmn.Asset)
- func (s *TemplateSystem) RegisterAssetJsContent(content string) *cmn.Asset
- func (s *TemplateSystem) RegisterAssetJsFilepath(filepath string) (*cmn.Asset, error)
- func (s *TemplateSystem) RegisterAssetJsURL(src string) (*cmn.Asset, error)
- type TranscludeFunc
Constants ¶
This section is empty.
Variables ¶
var HtmlBooleanAttributes = map[string]bool{}
var HtmlVoidElements = map[string]bool{}
HtmlVoidElements Void elements are those that can't have any contents.
Functions ¶
func CreateBoolMap ¶
func CreateComponent ¶
func CreateComponent(node *Node, attrs *Attributes, t *Compiler)
CreateComponent cria um componente. Um component é uma estrutura reutilizável que possui características especiais
func CreateNodeIdentifier ¶
CreateNodeIdentifier creates a function that when invoked, adds a class so that a node can be identified
func HashSha512Base64 ¶
HashSha512Base64 return a base64-encoded cryptographic hash of a resource using SHA-512 hash algorithm
func HashXXH64 ¶
HashXXH64 Make a fingerprint. Compute a non-cryptographic XXH64 checksum of strings
Encoded using Base64 URLSafe
func HashXXH64Hex ¶
HashXXH64Hex computing the XXH64 checksum of strings
func HtmlEscape ¶
func NormalizeName ¶
func TestCompile ¶
func TestCompile(t *testing.T, template string, static []string, globalDirectives *Directives) (*Compiled, *Compiler)
TestCompile compiles a template and already tests the expected output
func TestRender ¶
func TestRender(t *testing.T, compiled *Compiled, values map[string]interface{}, expected string) (*Rendered, *Scope)
TestRender renders a compiled and already tests the expected result
func TestTemplate ¶
func TestUnindentedTemplate ¶
Types ¶
type Attribute ¶
type Attribute struct { Name string Value string Namespace string Normalized string // name normalized }
Attribute representa um atributo html
type Attributes ¶
Attributes abstração dos atributos de um Node html
func (*Attributes) AddClass ¶
func (a *Attributes) AddClass(value string)
AddClass Adds the specified class(es) to element
func (*Attributes) Clone ¶
func (a *Attributes) Clone() *Attributes
Clone Uso interno, faz uma cópia dos atributos para ser usado em tempo de execução
func (*Attributes) Get ¶
func (a *Attributes) Get(name string) (value string)
func (*Attributes) GetAttribute ¶
func (a *Attributes) GetAttribute(name string) *Attribute
func (*Attributes) GetOrDefault ¶
func (a *Attributes) GetOrDefault(name string, dfault string) (value string)
func (*Attributes) HasClass ¶
func (a *Attributes) HasClass(value string) bool
HasClass Determine whether the element is assigned the given class.
func (*Attributes) Remove ¶
func (a *Attributes) Remove(attr *Attribute)
func (*Attributes) RemoveClass ¶
func (a *Attributes) RemoveClass(value string)
RemoveClass Remove a single class or multiple classes from element
func (*Attributes) Render ¶
func (a *Attributes) Render() *Rendered
Render the attributes sorted by name. Boolean attributes (no value) are always rendered at the end
&Rendered{ Static: *[]string{ ` attribute-one="`, `" attribute-two="`, `" class="`, `" boolean-attr-one boolean-attr-2`, } Dynamics: []interface{}{ "value-1", "value-2" "class-1 class-", } }
func (*Attributes) Set ¶
func (a *Attributes) Set(key string, value string)
type Compiled ¶
type Compiled struct { Assets []*cmn.Asset // Reference to all resources that can be used by this compiled // contains filtered or unexported fields }
Compiled structure representing a Compiled template
func Interpolate ¶
Interpolate Compiles a string with markup into an interpolation function.
GO INTERPOLATION ( {value} or !{value} )
<element attribute="{return value}"> <element attribute="xpto {escape safe}"> <element attribute="xpto !{escape unsafe}"> <element attribute="!{escape unsafe}"> <element>{escape safe}</element> <element>!{escape unsafe}</element>
exp = Interpolate('Hello {name}!'); exp.Exec({name:'Syntax'}).String() == "Hello Syntax!"
func (*Compiled) Fingerprint ¶
Fingerprint GetIndex static fingerprint
type Compiler ¶
type Compiler struct { System *TemplateSystem // Reference to the instance that generated this TemplateSystem compiler Directives *Directives // The directives registered to run in this build Assets map[*cmn.Asset]bool // The possible resources that will be used by this template Context *Context // allows directives to save context information during compilation Sequence *Sequence // contains filtered or unexported fields }
Compiler scope of html template being compiled
func NewCompiler ¶
func NewCompiler(ts *TemplateSystem) *Compiler
func (*Compiler) RegisterAsset ¶
RegisterAsset register an asset that can be used in this template
func (*Compiler) RegisterAssetJsContent ¶
RegisterAssetJsContent register an anonymous javascript that can be used in this template
func (*Compiler) RegisterAssetJsFilepath ¶
RegisterAssetJsFilepath register an existing javascript in the filesystem being used by this template
func (*Compiler) RegisterAssetJsURL ¶
RegisterAssetJsURL registers an external javascript being used by this template
func (*Compiler) SafeRemove ¶
SafeRemove remove o node de forma segura
type ComponentFunc ¶
type ComponentFunc func(scope *Scope)
type Context ¶
type Context struct { Data map[string]interface{} Timing *cmn.ServerTiming }
Context simple framework for accessing the compile and run context.
Context can be used by directives to exchange or expose execution information
func NewContext ¶
func NewContext() *Context
func (*Context) GetOrDefault ¶
type Directive ¶
type Directive struct { Name string // When there are multiple Directives defined on a single HTML node, sometimes it is necessary to specify the order // in which the Directives are applied. The Priority is used to sort the Directives before their Compile functions // get called. Directive with greater numerical priority are compiled first. The default priority is 0. Priority int Restrict DirectiveRestrict // Quando possuir template, a diretiva é Terminal Template string TemplatePath string // Assets e acesso ao fs.Sys, um diretório para permitir carregamento em tempo de compilação Assets fs.FS // true - transclude the transcludeSlots (i.e. the child nodes) of the directive's element. // 'element' - transclude the whole of the directive's element including any directives on this element that are // defined at a lower priority than this directive. When used, the template property is ignored. // {...} (an object hash): - map elements of the transcludeSlots onto transclusion "slots" in the template. Transclude interface{} // true, false, map[string]string // If set to true then the current priority will be the last set of Directives which will execute (any Directive at // the current priority will still execute as the order of execution on same priority is undefined). // Note that expressions and other Directive used in the directive's template will also be excluded from execution. // Quando a directiva é terminal: // 1. O Transclude fica disponível para o método Process // 2. O método Process pode retornar um *Rendered Terminal bool // false (default): No scope will be created for the directive. The directive will use its root's scope. // true: A new child scope that prototypically inherits from its root will be created for the directive's element. // If multiple Directives on the same element request a new scope, only one new scope is created. Scope bool Compile DirectiveCompileFunc Controller DirectiveControllerFunc Process DirectiveProcessFunc Leave DirectiveLeaveFunc }
Directive @TODO: Salvar a referencia de todas as diretivas cadastradas, não permitir que a mesma diretiva seja redefinida ou recarregada. Sempre usar a mesma implementação existente em memória. Todas as diretivas que possuem conteúdo devem resultar em um Compiled
type DirectiveCompileFunc ¶
type DirectiveCompileFunc func(node *Node, attrs *Attributes, c *Compiler) (*DirectiveMethods, error)
DirectiveCompileFunc uma funcão que visita um elemento html e pode realizar ajustes no template em tempo de compilação
type DirectiveControllerFunc ¶
type DirectiveControllerFunc func(scope *Scope)
DirectiveControllerFunc função executada para permitir controlar
type DirectiveLeaveFunc ¶
type DirectiveLeaveFunc func(scope *Scope)
DirectiveLeaveFunc função executada após a renderização do elemento associado a uma diretiva
type DirectiveLeaveInfo ¶
type DirectiveLeaveInfo struct {
// contains filtered or unexported fields
}
type DirectiveMethods ¶
type DirectiveMethods struct { Controller DirectiveControllerFunc Process DirectiveProcessFunc Leave DirectiveLeaveFunc }
type DirectiveProcessFunc ¶
type DirectiveProcessFunc func(scope *Scope, attr *Attributes, transclude TranscludeFunc) (rendered *Rendered)
DirectiveProcessFunc função executada antes da renderização do elemento associado a uma diretiva Quando a directiva é transclude, o conteúdo original é substituido em tempo de execução pelo Rendered retornado
type DirectiveProcessInfo ¶
type DirectiveProcessInfo struct {
// contains filtered or unexported fields
}
type DirectiveRestrict ¶
type DirectiveRestrict uint8
DirectiveRestrict The directive must be found in specific location.
const ( ELEMENT DirectiveRestrict = 1 << iota // element name ATTRIBUTE // attribute )
type Directives ¶
type Directives struct {
// contains filtered or unexported fields
}
Directives group the list of registered directives
func (*Directives) Contains ¶
func (d *Directives) Contains(directive *Directive) bool
Contains verifica se essa directiva já está registrada nessa lista
func (*Directives) NewChild ¶
func (d *Directives) NewChild() *Directives
NewChild cria uma nova lista, que mantém referencia para a lista atual
type DirectivesByPriority ¶
type DirectivesByPriority []*Directive
func (DirectivesByPriority) Len ¶
func (l DirectivesByPriority) Len() int
func (DirectivesByPriority) Less ¶
func (l DirectivesByPriority) Less(i, j int) bool
func (DirectivesByPriority) Swap ¶
func (l DirectivesByPriority) Swap(i, j int)
type Dynamic ¶
type Dynamic interface { // Exec a function that takes a scope argument, and returns a list of dynamic content. // @return nil, string, *Compiled, *Rendered Exec(scope *Scope) interface{} }
Dynamic represents a dynamic part of a Compiled
type DynamicCompiled ¶
type DynamicCompiled struct {
Compiled *Compiled
}
DynamicCompiled um dynamic que apenas executa um compiled
func (*DynamicCompiled) Exec ¶
func (d *DynamicCompiled) Exec(scope *Scope) interface{}
type DynamicDirectives ¶
type DynamicDirectives struct {
// contains filtered or unexported fields
}
DynamicDirectives parte dinamica que executa as diretivas de um Node
func (*DynamicDirectives) Exec ¶
func (nd *DynamicDirectives) Exec(scope *Scope) interface{}
type DynamicFunc ¶
type DynamicFunc func(scope *Scope) interface{}
DynamicFunc permite usar uma função como um Dynamic
func (DynamicFunc) Exec ¶
func (f DynamicFunc) Exec(scope *Scope) interface{}
type DynamicInterpolate ¶
type DynamicInterpolate struct {
// contains filtered or unexported fields
}
DynamicInterpolate parte dinamica de execução de uma expressão
func (*DynamicInterpolate) Exec ¶
func (d *DynamicInterpolate) Exec(scope *Scope) interface{}
type DynamicInterpolateEscaped ¶
type DynamicInterpolateEscaped struct {
// contains filtered or unexported fields
}
DynamicInterpolateEscaped parte dinamica de execução de uma expressão
func (*DynamicInterpolateEscaped) Exec ¶
func (d *DynamicInterpolateEscaped) Exec(scope *Scope) interface{}
type Expression ¶
type Expression struct {
// contains filtered or unexported fields
}
func ParseExpression ¶
func ParseExpression(exp string) (*Expression, error)
ParseExpression process a single expression
func (*Expression) EvalBool ¶
func (e *Expression) EvalBool(scope *Scope) bool
func (*Expression) EvalString ¶
func (e *Expression) EvalString(scope *Scope) string
func (*Expression) Exec ¶
func (e *Expression) Exec(scope *Scope) interface{}
type Node ¶
type Node struct {
Parent, FirstChild, LastChild, PrevSibling, NextSibling *Node
Type NodeType
Data string
DataAtom atom.Atom
Namespace string
Attributes *Attributes
//AttrList []*Attribute
File string
Line int
Column int
}
A Node consists of a NodeType and some Data (tag name for element nodes, content for text) and are part of a tree of Nodes. Element nodes may also have a Namespace and contain a slice of Attributes. Data is unescaped, so that it looks like "a<b" rather than "a<b". For element nodes, DataAtom is the atom for Data, or zero if Data is not a known tag name.
An empty Namespace implies a "http://www.w3.org/1999/xhtml" namespace. Similarly, "math" is short for "http://www.w3.org/1998/Math/MathML", and "svg" is short for "http://www.w3.org/2000/svg".
func Parse ¶
Parse returns the parse tree for the HTML from the given content.
The input is assumed to be UTF-8 encoded.
func (*Node) AppendChild ¶
AppendChild adds a node c as a child of n.
It will panic if c already has a parent or siblings.
func (*Node) ExtractChildren ¶
ExtractChildren returns a new parent to the children of the current node
func (*Node) GetChildNodes ¶
GetChildNodes returns a collection (list) of an elements's child nodes.
func (*Node) RemoveChild ¶
RemoveChild removes a node c that is a child of n. Afterwards, c will have no parent and no siblings.
It will panic if c's parent is not n.
func (*Node) ReplaceByText ¶
ReplaceByText used for element transclude, replace current element with plain text, extracting all node data to a separate element
func (*Node) Transverse ¶
Transverse run callback for node and all its children, until callback returns true
@TODO: Alterar o algoritmo para o formato enter() exit(). node.transverse(func(enter){ /*before*/ enter() /*after*/ })
type NodeType ¶
type NodeType uint32
A NodeType is the type of a Node.
const ( ErrorNode NodeType = iota TextNode DocumentNode ElementNode CommentNode DoctypeNode // RawNode nodes are not returned by the parser, but can be part of the // Node tree passed to func Render to insert raw HTML (without escaping). // If so, this package makes no guarantee that the rendered HTML is secure // (from e.g. Cross Site Scripting attacks) or well-formed. RawNode )
type RegexMatch ¶
type RegexMatch struct {
// contains filtered or unexported fields
}
func RegexExec ¶
func RegexExec(re *regexp.Regexp, input string) *RegexMatch
RegexExec https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
func RegexExecAll ¶
func RegexExecAll(re *regexp.Regexp, input string) []*RegexMatch
type Rendered ¶
type Rendered struct { Static *[]string `json:"s"` // a list of literal strings Dynamics []interface{} `json:"d"` // nil, string, Rendered Fingerprint string `json:"f"` Root bool `json:"r"` Assets []string `json:"a"` // all the resources needed by that part }
Rendered structure of a Compiled
type Scope ¶
type Scope struct { Context *Context // allows directives to save context information during execution // contains filtered or unexported fields }
func NewRootScope ¶
func NewRootScope() *Scope
func (*Scope) Fetch ¶
func (s *Scope) Fetch(key interface{}) interface{}
Fetch used by expressions https://github.com/antonmedv/expr/blob/master/docs/Optimizations.md#reduced-use-of-reflect
type Sequence ¶
type Sequence struct { Salt string // contains filtered or unexported fields }
Sequence identifier generator utility qeu ensures that all executions have the same result
type TemplateSystem ¶
type TemplateSystem struct { Loader func(filepath string) (string, error) Directives *Directives Assets map[*cmn.Asset]bool // All Assets that referenced in this system }
func (*TemplateSystem) Compile ¶
func (s *TemplateSystem) Compile(filepath string) (*Compiled, *Context, error)
func (*TemplateSystem) Load ¶
func (s *TemplateSystem) Load(filepath string) (string, error)
Load load an html file
func (*TemplateSystem) NewScope ¶
func (s *TemplateSystem) NewScope() *Scope
NewScope creates a new scope that can be used to render a compiled
func (*TemplateSystem) Register ¶
func (s *TemplateSystem) Register(directives ...*Directive)
Register a global directive
func (*TemplateSystem) RegisterAsset ¶
func (s *TemplateSystem) RegisterAsset(asset *cmn.Asset)
RegisterAsset register an asset
func (*TemplateSystem) RegisterAssetJsContent ¶
func (s *TemplateSystem) RegisterAssetJsContent(content string) *cmn.Asset
RegisterAssetJsContent register an anonymous javascript
func (*TemplateSystem) RegisterAssetJsFilepath ¶
func (s *TemplateSystem) RegisterAssetJsFilepath(filepath string) (*cmn.Asset, error)
RegisterAssetJsFilepath registers an existing javascript on the filesystem being used by this system
func (*TemplateSystem) RegisterAssetJsURL ¶
func (s *TemplateSystem) RegisterAssetJsURL(src string) (*cmn.Asset, error)
RegisterAssetJsURL register an javascript asset by url
type TranscludeFunc ¶
TranscludeFunc função disponível no método Process quando a directiva possui transclude