Documentation
¶
Index ¶
- func IsEmptyTree(n Node) bool
- type ActionNode
- type AdditiveExprNode
- type Arguments
- func (a *Arguments) Get(argumentIndex int) reflect.Value
- func (a *Arguments) IsSet(argumentIndex int) bool
- func (a *Arguments) NumOfArguments() int
- func (a *Arguments) Panicf(format string, v ...interface{})
- func (a *Arguments) ParseInto(ptrs ...interface{}) error
- func (a *Arguments) RequireNumOfArguments(funcname string, min, max int)
- func (a *Arguments) Runtime() *Runtime
- type BlockNode
- type BlockParameter
- type BlockParameterList
- type BoolNode
- type BranchNode
- type Cache
- type CallArgs
- type CallExprNode
- type ChainNode
- type CommandNode
- type ComparativeExprNode
- type Expression
- type FieldNode
- type Func
- type IdentifierNode
- type IfNode
- type InMemLoader
- type IncludeNode
- type IndexExprNode
- type ListNode
- type Loader
- type LogicalExprNode
- type MultiplicativeExprNode
- type NilNode
- type Node
- type NodeBase
- type NodeType
- type NotExprNode
- type NumberNode
- type NumericComparativeExprNode
- type OSFileSystemLoader
- type Option
- func DevelopmentMode(mode bool) Option
- func InDevelopmentMode() Option
- func WithCache(c Cache) Option
- func WithCommentDelims(left, right string) Option
- func WithDelims(left, right string) Option
- func WithSafeWriter(w SafeWriter) Option
- func WithTemplateNameExtensions(extensions []string) Option
- func РасширенияШаблонов(extensions []string) Option
- func РежимРазработки() Option
- type PipeNode
- type Pos
- type RangeNode
- type Ranger
- type Renderer
- type RendererFunc
- type ReturnNode
- type Runtime
- func (r *Runtime) Context() reflect.Value
- func (state *Runtime) Let(name string, val interface{})
- func (state *Runtime) LetGlobal(name string, val interface{})
- func (state *Runtime) MustResolve(name string) reflect.Value
- func (state *Runtime) Resolve(name string) reflect.Value
- func (state *Runtime) Set(name string, val interface{}) error
- func (state *Runtime) SetOrLet(name string, val interface{})
- func (w Runtime) Write(b []byte) (int, error)
- func (st *Runtime) YieldBlock(name string, context interface{})
- type SafeWriter
- type Set
- func (s *Set) AddGlobal(key string, i interface{}) *Set
- func (s *Set) AddGlobalFunc(key string, fn Func) *Set
- func (s *Set) GetTemplate(templatePath string) (t *Template, err error)
- func (s *Set) LookupGlobal(key string) (val interface{}, found bool)
- func (s *Set) Parse(templatePath, contents string) (template *Template, err error)
- func (s *Set) ДобавитьБлок(имяБлока string, б *BlockNode)
- func (s *Set) ДобавитьГлобально(key string, i interface{}) *Set
- func (s *Set) ДобавитьДеревоШаблона(имяШаблона string, t *Template)
- func (s *Set) ДобавитьКонтентБлок(каталогШаблоновРоли string, ...) (*Template, error)
- func (s *Set) ДобавитьФункции(НаборФункций КартаФункций) *Set
- func (s *Set) ДобавитьФункцию(key string, fn Func) *Set
- func (s *Set) НайтиБлок(имяБлока string) *BlockNode
- func (s *Set) Парсинг(имяШаблона string, текстШаблона string, ...) (t *Template, err error)
- func (набор *Set) ПарсингДиректории(директорияШаблонов string)
- func (набор *Set) ПарсингДиректорииШаблонов()
- func (s *Set) ПарсингШаблона(templatePath string, получитьИзКэша bool) (t *Template, err error)
- func (s *Set) ПарсингШаблонаСДиска(путьКонтентШаблона string) (t *Template, err error)
- func (s *Set) ПоказатьШаблоныйВКэше()
- type SetNode
- type SliceExprNode
- type StringNode
- type Template
- type TernaryExprNode
- type TextNode
- type TryNode
- type UnderscoreNode
- type VarMap
- type YieldNode
- type КартаФункций
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type ActionNode ¶
ActionNode holds an action (something bounded by delimiters). Control actions have their own nodes; ActionNode represents simple ones such as field evaluations and parenthesized pipelines.
func (*ActionNode) String ¶
func (a *ActionNode) String() string
type AdditiveExprNode ¶
type AdditiveExprNode struct {
// contains filtered or unexported fields
}
AdditiveExprNode represents an add or subtract expression ex: expression ( '+' | '-' ) expression
type Arguments ¶
type Arguments struct {
// contains filtered or unexported fields
}
Arguments holds the arguments passed to jet.Func.
func (*Arguments) Get ¶
Get gets an argument by index.
func (*Arguments) IsSet ¶
IsSet checks whether an argument is set or not. It behaves like the build-in isset function.
func (*Arguments) NumOfArguments ¶
NumOfArguments returns the number of arguments
func (*Arguments) Panicf ¶
Panicf panics with formatted error message.
func (*Arguments) ParseInto ¶
ParseInto parses the arguments into the provided pointers. It returns an error if the number of pointers passed in does not equal the number of arguments, if any argument's value is invalid according to Go's reflect package, if an argument can't be used as the value the pointer passed in at the corresponding position points to, or if an unhandled pointer type is encountered. Allowed pointer types are pointers to interface{}, int, int64, float64, bool, string, time.Time, reflect.Value, []interface{}, map[string]interface{}. If a pointer to a reflect.Value is passed in, the argument be assigned as-is to the value pointed to. For pointers to int or float types, type conversion is performed automatically if necessary.
func (*Arguments) RequireNumOfArguments ¶
RequireNumOfArguments panics if the number of arguments is not in the range specified by min and max. In case there is no minimum pass -1, in case there is no maximum pass -1 respectively.
type BlockNode ¶
type BlockNode struct { NodeBase //The line number in the input. Deprecated: Kept for compatibility. Name string //The name of the template (unquoted). Parameters *BlockParameterList Expression Expression //The command to evaluate as dot for the template. List *ListNode Content *ListNode }
BlockNode represents a {{block }} action.
type BlockParameter ¶
type BlockParameter struct { Identifier string Expression Expression }
type BlockParameterList ¶
type BlockParameterList struct { NodeBase List []BlockParameter }
func (*BlockParameterList) Param ¶
func (bplist *BlockParameterList) Param(name string) (Expression, int)
func (*BlockParameterList) String ¶
func (bplist *BlockParameterList) String() (str string)
type BoolNode ¶
BoolNode holds a boolean constant.
type BranchNode ¶
type BranchNode struct { NodeBase Set *SetNode Expression Expression List *ListNode ElseList *ListNode }
BranchNode is the common representation of if, range, and with.
func (*BranchNode) String ¶
func (b *BranchNode) String() string
type Cache ¶
type Cache interface { // Get fetches a template from the cache. If Get returns nil, the same path with a different extension will be tried. // If Get() returns nil for all configured extensions, the same path and extensions will be tried on the Set's Loader. Get(templatePath string) *Template НайтиБлок(имяБлока string) *BlockNode // Put places the result of parsing a template "file"/string in the cache. Put(templatePath string, t *Template) ДобавитьБлок(имяБлока string, блок *BlockNode) Обойти(f func(key, value any) bool) }
Cache is the interface Jet uses to store and retrieve parsed templates.
type CallArgs ¶
type CallArgs struct { Exprs []Expression HasPipeSlot bool }
type CallExprNode ¶
type CallExprNode struct { NodeBase BaseExpr Expression CallArgs }
CallExprNode represents a call expression ex: expression '(' (expression (',' expression)* )? ')'
func (*CallExprNode) String ¶
func (s *CallExprNode) String() string
type ChainNode ¶
ChainNode holds a term followed by a chain of field accesses (identifier starting with '.'). The names may be chained ('.x.y'). The periods are dropped from each ident.
func (*ChainNode) Add ¶
Add adds the named field (which should start with a period) to the end of the chain.
type CommandNode ¶
type CommandNode struct { NodeBase CallExprNode }
CommandNode holds a command (a pipeline inside an evaluating action).
func (*CommandNode) String ¶
func (c *CommandNode) String() string
type ComparativeExprNode ¶
type ComparativeExprNode struct {
// contains filtered or unexported fields
}
ComparativeExprNode represents a comparative expression ex: expression ( '==' | '!=' ) expression
type FieldNode ¶
FieldNode holds a field (identifier starting with '.'). The names may be chained ('.x.y'). The period is dropped from each ident.
type IdentifierNode ¶
IdentifierNode holds an identifier.
func (*IdentifierNode) String ¶
func (i *IdentifierNode) String() string
type IfNode ¶
type IfNode struct {
BranchNode
}
IfNode represents an {{если}} action and its commands.
type InMemLoader ¶
type InMemLoader struct {
// contains filtered or unexported fields
}
InMemLoader is a simple in-memory loader storing template contents in a simple map. InMemLoader normalizes paths passed to its methods by converting any input path to a slash-delimited path, turning it into an absolute path by prepending a "/" if neccessary, and cleaning it (see path.Clean()). It is safe for concurrent use. InMemLoader - это простой загрузчик в памяти, сохраняющий содержимое шаблона в виде простой карты. InMemLoader нормализует пути, передаваемые его методам, преобразуя любой входной путь в путь, разделенный косой чертой, // превращая его в абсолютный путь, добавляя "/", если это необходимо, и очищая его (см. path.Очистить()). Это безопасно для одновременного использования.
func (*InMemLoader) Delete ¶
func (l *InMemLoader) Delete(templatePath string)
Delete removes whatever contents are stored under the given path.
func (*InMemLoader) Dir ¶
func (l *InMemLoader) Dir() string
func (*InMemLoader) Exists ¶
func (l *InMemLoader) Exists(templatePath string) bool
Exists returns whether or not a template is indexed under this path.
func (*InMemLoader) Open ¶
func (l *InMemLoader) Open(templatePath string) (io.ReadCloser, error)
Open returns a template's contents, or an error if no template was added under this path using Set().
func (*InMemLoader) Set ¶
func (l *InMemLoader) Set(templatePath, contents string)
Set adds a template to the loader.
type IncludeNode ¶
type IncludeNode struct { NodeBase Name Expression Context Expression }
IncludeNode represents a {{шаблон }} action.
func (*IncludeNode) String ¶
func (t *IncludeNode) String() string
type IndexExprNode ¶
type IndexExprNode struct { NodeBase Base Expression Index Expression }
func (*IndexExprNode) String ¶
func (s *IndexExprNode) String() string
type ListNode ¶
ListNode holds a sequence of nodes.
type Loader ¶
type Loader interface { // Exists returns whether or not a template exists under the requested path. Exists(templatePath string) bool Dir() string // Open returns the template's contents or an error if something went wrong. // Calls to Open() will always be preceded by a call to Exists() with the same `templatePath`. // It is the caller's duty to close the template. Open(templatePath string) (io.ReadCloser, error) }
Loader is a minimal interface required for loading templates.
Jet will build an absolute path (with slash delimiters) before looking up templates by resolving paths in extends/import/include statements:
- `{{ extends "/bar.jet" }}` will make Jet look up `/bar.jet` in the Loader unchanged, no matter where it occurs (since it's an absolute path) - `{{ include("\views\bar.jet") }}` will make Jet look up `/views/bar.jet` in the Loader, no matter where it occurs - `{{ import "bar.jet" }}` in `/views/foo.jet` will result in a lookup of `/views/bar.jet` - `{{ extends "./bar.jet" }}` in `/views/foo.jet` will result in a lookup of `/views/bar.jet` - `{{ import "../views\bar.jet" }}` in `/views/foo.jet` will result in a lookup of `/views/bar.jet` - `{{ include("../bar.jet") }}` in `/views/foo.jet` will result in a lookup of `/bar.jet` - `{{ import "../views/../bar.jet" }}` in `/views/foo.jet` will result in a lookup of `/bar.jet`
This means that the same template will always be looked up using the same path.
Jet will also try appending multiple file endings for convenience: `{{ extends "/bar" }}` will lookup `/bar`, `/bar.jet`, `/bar.html.jet` and `/bar.jet.html` (in that order). To avoid unneccessary lookups, use the full file name in your templates (so the first lookup is always a hit, or override this list of extensions using Set.SetExtensions().
type LogicalExprNode ¶
type LogicalExprNode struct {
// contains filtered or unexported fields
}
LogicalExprNode represents a boolean expression, 'and' or 'or' ex: expression ( '&&' | '||' ) expression
type MultiplicativeExprNode ¶
type MultiplicativeExprNode struct {
// contains filtered or unexported fields
}
MultiplicativeExprNode represents a multiplication, division, or module expression ex: expression ( '*' | '/' | '%' ) expression
type NilNode ¶
type NilNode struct {
NodeBase
}
NilNode holds the special identifier 'nil' representing an untyped nil constant.
type Node ¶
type NodeType ¶
type NodeType int
NodeType identifies the type of a parse tree node.
const ( NodeText NodeType = iota //Plain text. NodeAction //A non-control action such as a field evaluation. NodeChain //A sequence of field accesses. NodeCommand //An element of a pipeline. NodeField //A field or method name. NodeIdentifier //An identifier; always a function name. NodeUnderscore //An underscore (discard in assignment, or slot in argument list for piped value) NodeList //A list of Nodes. NodePipe //A pipeline of commands. NodeSet //NodeWith //A with action. NodeInclude NodeBlock NodeYield NodeIf //An if action. NodeRange //A range action. NodeTry NodeReturn NodeString //A string constant. NodeNil //An untyped nil constant. NodeNumber //A numerical constant. NodeBool //A boolean constant. NodeAdditiveExpr NodeMultiplicativeExpr NodeComparativeExpr NodeNumericComparativeExpr NodeLogicalExpr NodeCallExpr NodeNotExpr NodeTernaryExpr NodeIndexExpr NodeSliceExpr )
type NotExprNode ¶
type NotExprNode struct { NodeBase Expr Expression }
NotExprNode represents a negate expression ex: '!' expression
func (*NotExprNode) String ¶
func (s *NotExprNode) String() string
type NumberNode ¶
type NumberNode struct { NodeBase 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. }
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) String ¶
func (n *NumberNode) String() string
type NumericComparativeExprNode ¶
type NumericComparativeExprNode struct {
// contains filtered or unexported fields
}
NumericComparativeExprNode represents a numeric comparative expression ex: expression ( '<' | '>' | '<=' | '>=' ) expression
type OSFileSystemLoader ¶
type OSFileSystemLoader struct {
// contains filtered or unexported fields
}
OSFileSystemLoader implements Loader interface using OS file system (os.File).
func NewOSFileSystemLoader ¶
func NewOSFileSystemLoader(dirPath string) *OSFileSystemLoader
NewOSFileSystemLoader returns an initialized OSFileSystemLoader.
func (*OSFileSystemLoader) Dir ¶
func (l *OSFileSystemLoader) Dir() string
func (*OSFileSystemLoader) Exists ¶
func (l *OSFileSystemLoader) Exists(templatePath string) bool
Exists returns true if a file is found under the template path after converting it to a file path using the OS's path seperator and joining it with the loader's directory path.
func (*OSFileSystemLoader) Open ¶
func (l *OSFileSystemLoader) Open(templatePath string) (io.ReadCloser, error)
Open returns the result of `os.Open()` on the file located using the same logic as Exists().
type Option ¶
type Option func(*Set)
Option is the type of option functions that can be used in NewSet().
func DevelopmentMode ¶
DevelopmentMode returns an option function that sets development mode on or off. "On" means the cache will always be bypassed and every template lookup will go to the loader.
func InDevelopmentMode ¶
func InDevelopmentMode() Option
InDevelopmentMode returns an option function that toggles development mode on, meaning the cache will always be bypassed and every template lookup will go to the loader.
func WithCache ¶
WithCache returns an option function that sets the cache to use for template parsing results. Use InDevelopmentMode() to disable caching of parsed templates. By default, Jet uses a concurrency-safe in-memory cache that holds templates forever. // With Cache возвращает функцию option, которая настраивает использование кэша для результатов анализа шаблонов. // Используйте в режиме разработки(), чтобы отключить кэширование проанализированных шаблонов. По умолчанию Jet использует защищенный от параллелизма кэш в памяти, в котором шаблоны хранятся вечно
func WithCommentDelims ¶
WithCommentDelims returns an option function that sets the comment delimiters to the specified strings. Parsed templates will inherit the settings. Not setting them leaves them at the default: `{*` and `*}`.
func WithDelims ¶
WithDelims returns an option function that sets the delimiters to the specified strings. Parsed templates will inherit the settings. Not setting them leaves them at the default: `{{` and `}}`.
func WithSafeWriter ¶
func WithSafeWriter(w SafeWriter) Option
WithSafeWriter returns an option function that sets the escaping function to use when executing templates. By default, Jet uses a writer that takes care of HTML escaping. Pass nil to disable escaping.
func WithTemplateNameExtensions ¶
WithTemplateNameExtensions returns an option function that sets the extensions to try when looking up template names in the cache or loader. Default extensions are `""` (no extension), `".jet"`, `".html.jet"`, `".jet.html"`. Extensions will be tried in the order they are defined in the slice. WithTemplateNameExtensions panics when you pass in a nil or empty slice.
func РасширенияШаблонов ¶
// WРасширенияШаблонов возвращает функцию option, которая устанавливает, какие расширения следует использовать при поиске по именам шаблонов в кэше или загрузчике. Расширениями по умолчанию являются """" (без расширения), "".jet"", "".html.jet"", "".jet.html "`. Расширения будут опробованы в том порядке, в котором они определены в срезе. WithTemplateNameExtensions вызывает панику, когда вы вводите нулевой или пустой фрагмент. расширение добавляеться к переданому в функцию ПарсингШаблона имени ф
type PipeNode ¶
type PipeNode struct { NodeBase //The line number in the input. Deprecated: Kept for compatibility. Cmds []*CommandNode //The commands in lexical order. }
PipeNode holds a pipeline with optional declaration
type Pos ¶
type Pos int
Pos represents a byte position in the original input text from which this template was parsed.
type RangeNode ¶
type RangeNode struct {
BranchNode
}
RangeNode represents a {{обход}} action and its commands.
type Ranger ¶
type Ranger interface { // Range calls should return a key, a value and a done bool to indicate // whether there are more values to be generated. // // When the done flag is true, then the loop ends. Range() (reflect.Value, reflect.Value, bool) // ProvidesIndex should return true if keys are produced during Range() // calls. This call should be idempotent across Range() calls (i.e. // its return value must not change during an iteration). ProvidesIndex() bool }
Ranger describes an interface for types that iterate over something. Implementing this interface means the ranger will be used when it's encountered on the right hand side of a range's "let" expression.
Example ¶
ExampleRanger demonstrates how to write a custom template ranger.
package main import ( "fmt" "os" "reflect" ) // exampleCustomBenchRanger satisfies the Ranger interface, generating fixed // data. type exampleCustomRanger struct { i int } // Type assertion to verify exampleCustomRanger satisfies the Ranger interface. var _ Ranger = (*exampleCustomRanger)(nil) func (ecr *exampleCustomRanger) ProvidesIndex() bool { // Return false if 'k' can't be filled in Range(). return true } func (ecr *exampleCustomRanger) Range() (k reflect.Value, v reflect.Value, done bool) { if ecr.i >= 3 { done = true return } k = reflect.ValueOf(ecr.i) v = reflect.ValueOf(fmt.Sprintf("custom ranger %d", ecr.i)) ecr.i += 1 return } // ExampleRanger demonstrates how to write a custom template ranger. func main() { // Error handling ignored for brevity. // // Setup template and rendering. loader := NewInMemLoader() loader.Set("template", "{{range k := ecr }}{{k}}:{{.}}; {{end}}") set := NewSet(loader, WithSafeWriter(nil)) t, _ := set.GetTemplate("template") // Pass a custom ranger instance as the 'ecr' var. vars := VarMap{"ecr": reflect.ValueOf(&exampleCustomRanger{})} // Execute template. _ = t.Execute(os.Stdout, vars, nil) }
Output: 0:custom ranger 0; 1:custom ranger 1; 2:custom ranger 2;
type Renderer ¶
type Renderer interface {
Render(*Runtime)
}
Renderer is used to detect if a value has its own rendering logic. If the value an action evaluates to implements this interface, it will not be printed using github.com/CloudyKit/fastprinter, instead, its Render() method will be called and is responsible for writing the value to the render output.
type RendererFunc ¶
type RendererFunc func(*Runtime)
RendererFunc func implementing interface Renderer
func (RendererFunc) Render ¶
func (renderer RendererFunc) Render(r *Runtime)
type ReturnNode ¶
type ReturnNode struct { NodeBase Value Expression }
func (*ReturnNode) String ¶
func (n *ReturnNode) String() string
type Runtime ¶
type Runtime struct {
// contains filtered or unexported fields
}
Runtime this type holds the state of the execution of an template
func (*Runtime) Context ¶
Context returns the current context value
func (*Runtime) Let ¶
Let initialises a variable in the current template scope (possibly shadowing an existing variable of the same name in a parent scope).
func (*Runtime) LetGlobal ¶
LetGlobal sets or initialises a variable in the top-most template scope.
func (*Runtime) MustResolve ¶
Resolve calls resolve() and panics if there is an error.
func (*Runtime) Resolve ¶
Resolve calls resolve() and ignores any errors, meaning it may return a zero reflect.Value.
func (*Runtime) Set ¶
Set sets an existing variable in the template scope it lives in.
func (*Runtime) SetOrLet ¶
SetOrLet calls Set() (if a variable with the given name is visible from the current scope) or Let() (if there is no variable with the given name in the current or any parent scope).
type SafeWriter ¶
SafeWriter is a function that writes bytes directly to the render output, without going through Jet's auto-escaping phase. Use/implement this if content should be escaped differently or not at all (see raw/unsafe builtins).
type Set ¶
type Set struct { JsБлоки Cache // contains filtered or unexported fields }
Set is responsible to load, parse and cache templates. Every Jet template is associated with a Set. Set отвечает за загрузку, синтаксический анализ и кэширование шаблонов. Каждый шаблон Jet связан с набором.
func NewSet ¶
NewSet returns a new Set relying on loader. NewSet panics if a nil Loader is passed.
func (*Set) AddGlobal ¶
AddGlobal adds a global variable into the Set, overriding any value previously set under the specified key. It returns the Set it was called on to allow for method chaining. // Add Global добавляет глобальную переменную в Set, переопределяющую любое значение, ранее установленное в соответствии с указанным ключом. Она возвращает Set, для которого она была вызвана, чтобы разрешить объединение методов в цепочку.
func (*Set) AddGlobalFunc ¶
AddGlobalFunc adds a global function into the Set, overriding any function previously set under the specified key. It returns the Set it was called on to allow for method chaining.
func (*Set) GetTemplate ¶
GetTemplate tries to find (and parse, if not yet parsed) the template at the specified path.
For example, GetTemplate("catalog/products.list") with extensions set to []string{"", ".html.jet",".jet"} will try to look for:
- catalog/products.list
- catalog/products.list.html.jet
- catalog/products.list.jet
in the set's templates cache, and if it can't find the template it will try to load the same paths via the loader, and, if parsed successfully, cache the template (unless running in development mode).
func (*Set) LookupGlobal ¶
LookupGlobal returns the global variable previously set under the specified key. It returns the nil interface and false if no variable exists under that key. // Функция Lookup Global возвращает глобальную переменную, ранее установленную в соответствии с указанным ключом. Она возвращает интерфейс nil и значение false, если под этим ключом не существует переменной.
func (*Set) Parse ¶
Parse parses `contents` as if it were located at `templatePath`, but won't put the result into the cache. Any referenced template (e.g. via `extends` or `import` statements) will be tried to be loaded from the cache. If a referenced template has to be loaded and parsed, it will also not be put into the cache after parsing. Parse анализирует "содержимое" так, как если бы оно было расположено в "templatePath", но не помещает результат в кэш. Будет предпринята попытка загрузить из кэша любой шаблон, на который ссылаются (например, с помощью инструкций "extends" или "import"). Если необходимо загрузить и проанализировать шаблон, на который ссылается ссылка, он также не будет помещен в кэш после синтаксического анализа.
func (*Set) ДобавитьБлок ¶
ДобавитьБлок - добавляет блоки глобальный кэш набора, сортируя блоки с js кодом, и обычные.
func (*Set) ДобавитьДеревоШаблона ¶
func (*Set) ДобавитьКонтентБлок ¶
func (s *Set) ДобавитьКонтентБлок(каталогШаблоновРоли string, путьКонтентШаблона string, имяКонтентБлока string) (*Template, error)
Возвращает найденный блок, который добавлен в виртуальный Контент блок путьКонтентШаблона = может быть не просто именем а содержать папки , "вложенныйКонтент/"+картаМаршрута[0],
имяКонтентБлока может быть или Контент, или имяОсновногоШаблона_контент
func (*Set) ДобавитьФункции ¶
func (s *Set) ДобавитьФункции(НаборФункций КартаФункций) *Set
func (*Set) ДобавитьФункцию ¶
// ДобавитьФункцию добавляет глобальную функцию в набор, переопределяя любую функцию, ранее установленную с помощью указанного ключа. Она возвращает набор, для которого она была вызвана, чтобы разрешить объединение методов в цепочку. вызывает под капотом s.ДобавитьГлобально(key, fn)
func (*Set) Парсинг ¶
func (*Set) ПарсингШаблона ¶
ПарсингШаблона пытается найти (и проанализировать, если еще не проанализирован) шаблон по указанному пути.
Например, ПарсингШаблона("каталог/products.list") с расширениями, установленными в []строку{"", ".html.jet",".jet"} попытается найти: 1. каталог/products.list 2. catalog/products.list.html.jet 3. catalog/products.list.jet
в кэше шаблонов набора, и если он не сможет найти шаблон, он попытается загрузить те же пути через загрузчик и, в случае успешного анализа, кэширует шаблон (если только он не запущен в режиме разработки).
func (*Set) ПарсингШаблонаСДиска ¶
type SetNode ¶
type SetNode struct { NodeBase Let bool IndexExprGetLookup bool Left []Expression Right []Expression }
SetNode represents a set action, ident( ',' ident)* '=' expression ( ',' expression )*
type SliceExprNode ¶
type SliceExprNode struct { NodeBase Base Expression Index Expression EndIndex Expression }
func (*SliceExprNode) String ¶
func (s *SliceExprNode) String() string
type StringNode ¶
type StringNode struct { NodeBase Quoted string //The original text of the string, with quotes. Text string //The string, after quote processing. }
StringNode holds a string constant. The value has been "unquoted".
func (*StringNode) String ¶
func (s *StringNode) String() string
type Template ¶
type Template struct { Name string // name of the template represented by the tree. ParseName string // name of the top-level template during parsing, for error messages. Root *ListNode // top-level root of the tree. // contains filtered or unexported fields }
Template is the representation of a single parsed template.
func (*Template) Execute ¶
Execute executes the template into w.
type TernaryExprNode ¶
type TernaryExprNode struct { NodeBase Boolean, Left, Right Expression }
TernaryExprNod represents a ternary expression, ex: expression '?' expression ':' expression
func (*TernaryExprNode) String ¶
func (s *TernaryExprNode) String() string
type TextNode ¶
TextNode holds plain text.
type TryNode ¶
type UnderscoreNode ¶
type UnderscoreNode struct {
NodeBase
}
UnderscoreNode is used for one of two things: - signals to discard the corresponding right side of an assignment - tells Jet where in a pipelined function call to inject the piped value
func (*UnderscoreNode) String ¶
func (i *UnderscoreNode) String() string
type VarMap ¶
func (VarMap) SetWriter ¶
func (scope VarMap) SetWriter(name string, v SafeWriter) VarMap
type YieldNode ¶
type YieldNode struct { NodeBase //The line number in the input. Deprecated: Kept for compatibility. Name string //The name of the template (unquoted). Parameters *BlockParameterList Expression Expression //The command to evaluate as dot for the template. Content *ListNode IsContent bool }
YieldNode represents a {{вставить}} action
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
examples
|
|
asset_packaging
+Build ignore
|
+Build ignore |
todos/src
+Build ignore
|
+Build ignore |
loaders
|
|