jet package - github.com/CloudyKit/jet/v6 - Go Packages

This section is empty.

This section is empty.

func IsEmptyTree(n Node) bool

IsEmptyTree reports whether this tree (node) is empty of everything but space.

type ActionNode struct {
	NodeBase
	Set  *SetNode
	Pipe *PipeNode
}

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.

type AdditiveExprNode struct {
	
}

AdditiveExprNode represents an add or subtract expression ex: expression ( '+' | '-' ) expression

func (node *AdditiveExprNode) String() string
type Arguments struct {
	
}

Arguments holds the arguments passed to jet.Func.

Get gets an argument by index.

func (a *Arguments) IsSet(argumentIndex int) bool

IsSet checks whether an argument is set or not. It behaves like the build-in isset function.

func (a *Arguments) NumOfArguments() int

NumOfArguments returns the number of arguments

func (a *Arguments) Panicf(format string, v ...interface{})

Panicf panics with formatted error message.

func (a *Arguments) ParseInto(ptrs ...interface{}) error

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 (a *Arguments) RequireNumOfArguments(funcname string, min, max int)

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.

func (a *Arguments) Runtime() *Runtime

Runtime get the Runtime context

type BlockNode struct {
	NodeBase        
	Name     string 

	Parameters *BlockParameterList
	Expression Expression 

	List    *ListNode
	Content *ListNode
}

BlockNode represents a {{block }} action.

type BlockParameter struct {
	Identifier string
	Expression Expression
}
type BlockParameterList struct {
	NodeBase
	List []BlockParameter
}
type BoolNode struct {
	NodeBase
	True bool 
}

BoolNode holds a boolean constant.

type BranchNode struct {
	NodeBase
	Set        *SetNode
	Expression Expression
	List       *ListNode
	ElseList   *ListNode
}

BranchNode is the common representation of if, range, and with.

type Cache interface {

	
	
	Get(templatePath string) *Template

	
	Put(templatePath string, t *Template)
}

Cache is the interface Jet uses to store and retrieve parsed templates.

type CallArgs struct {
	Exprs       []Expression
	HasPipeSlot bool
}
type CallExprNode struct {
	NodeBase
	BaseExpr Expression
	CallArgs
}

CallExprNode represents a call expression ex: expression '(' (expression (',' expression)* )? ')'

type ChainNode struct {
	NodeBase
	Node  Node
	Field []string 
}

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.

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).

type ComparativeExprNode struct {
	
}

ComparativeExprNode represents a comparative expression ex: expression ( '==' | '!=' ) expression

func (node *ComparativeExprNode) String() string
type Expression interface {
	Node
}
type FieldNode struct {
	NodeBase
	Ident []string 
}

FieldNode holds a field (identifier starting with '.'). The names may be chained ('.x.y'). The period is dropped from each ident.

Func function implementing this type is called directly, which is faster than calling through reflect. If a function is being called many times in the execution of a template, you may consider implementing a wrapper for that function implementing a Func.

type IdentifierNode struct {
	NodeBase
	Ident string 
}

IdentifierNode holds an identifier.

type IfNode struct {
	BranchNode
}

IfNode represents an {{if}} action and its commands.

type InMemLoader struct {
	
}

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.

func NewInMemLoader() *InMemLoader

NewInMemLoader return a new InMemLoader.

func (l *InMemLoader) Delete(templatePath string)

Delete removes whatever contents are stored under the given path.

Exists returns whether or not a template is indexed under this path.

Open returns a template's contents, or an error if no template was added under this path using Set().

func (l *InMemLoader) Set(templatePath, contents string)

Set adds a template to the loader.

type IncludeNode struct {
	NodeBase
	Name    Expression
	Context Expression
}

IncludeNode represents a {{include }} action.

type IndexExprNode struct {
	NodeBase
	Base  Expression
	Index Expression
}
type ListNode struct {
	NodeBase
	Nodes []Node 
}

ListNode holds a sequence of nodes.

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 struct {
	
}

LogicalExprNode represents a boolean expression, 'and' or 'or' ex: expression ( '&&' | '||' ) expression

func (node *LogicalExprNode) String() string
type MultiplicativeExprNode struct {
	
}

MultiplicativeExprNode represents a multiplication, division, or module expression ex: expression ( '*' | '/' | '%' ) expression

func (node *MultiplicativeExprNode) String() string
type NilNode struct {
	NodeBase
}

NilNode holds the special identifier 'nil' representing an untyped nil constant.

type Node interface {
	Type() NodeType
	String() string
	Position() Pos
	
}
type NodeBase struct {
	TemplatePath string
	Line         int
	NodeType
	Pos
}

NodeType identifies the type of a parse tree node.

const (
	NodeText       NodeType = iota 
	NodeAction                     
	NodeChain                      
	NodeCommand                    
	NodeField                      
	NodeIdentifier                 
	NodeUnderscore                 
	NodeList                       
	NodePipe                       
	NodeSet
	
	NodeInclude
	NodeBlock

	NodeYield

	NodeIf 

	NodeRange 
	NodeTry

	NodeReturn

	NodeString 
	NodeNil    
	NodeNumber 
	NodeBool   
	NodeAdditiveExpr
	NodeMultiplicativeExpr
	NodeComparativeExpr
	NodeNumericComparativeExpr
	NodeLogicalExpr
	NodeCallExpr
	NodeNotExpr
	NodeTernaryExpr
	NodeIndexExpr
	NodeSliceExpr
)
func (t NodeType) Type() NodeType

Type returns itself and provides an easy default implementation for embedding in a Node. Embedded in all non-trivial Nodes.

type NotExprNode struct {
	NodeBase
	Expr Expression
}

NotExprNode represents a negate expression ex: '!' expression

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.

type NumericComparativeExprNode struct {
	
}

NumericComparativeExprNode represents a numeric comparative expression ex: expression ( '<' | '>' | '<=' | '>=' ) expression

func (node *NumericComparativeExprNode) String() string
type OSFileSystemLoader struct {
	
}

OSFileSystemLoader implements Loader interface using OS file system (os.File).

func NewOSFileSystemLoader(dirPath string) *OSFileSystemLoader

NewOSFileSystemLoader returns an initialized OSFileSystemLoader.

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.

Open returns the result of `os.Open()` on the file located using the same logic as Exists().

Option is the type of option functions that can be used in NewSet().

func DevelopmentMode(mode bool) Option

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() 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(c Cache) Option

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.

func WithCommentDelims(left, right string) Option

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(left, right string) Option

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(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(extensions []string) Option

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.

type PipeNode struct {
	NodeBase                
	Cmds     []*CommandNode 
}

PipeNode holds a pipeline with optional declaration

Pos represents a byte position in the original input text from which this template was parsed.

func (p Pos) Position() Pos
type RangeNode struct {
	BranchNode
}

RangeNode represents a {{range}} action and its commands.

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.

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 }}
{{ range k := struct.RangerEface }}
{{k}} = {{.}}
{{- end }}`,
	)
	set := NewSet(loader, WithSafeWriter(nil))
	t, _ := set.GetTemplate("template")

	// Pass a custom ranger instance as the 'ecr' var, as well as in a struct field with type interface{}.
	vars := VarMap{
		"ecr":    reflect.ValueOf(&exampleCustomRanger{}),
		"struct": reflect.ValueOf(struct{ RangerEface interface{} }{RangerEface: &exampleCustomRanger{}}),
	}

	// Execute template.
	_ = t.Execute(os.Stdout, vars, nil)

}
Output:

0 = custom ranger 0
1 = custom ranger 1
2 = custom ranger 2

0 = custom ranger 0
1 = custom ranger 1
2 = custom ranger 2
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 func(*Runtime)

RendererFunc func implementing interface Renderer

func (renderer RendererFunc) Render(r *Runtime)
type ReturnNode struct {
	NodeBase
	Value Expression
}

Runtime this type holds the state of the execution of an template

Context returns the current context value

func (state *Runtime) Let(name string, val interface{})

Let initialises a variable in the current template scope (possibly shadowing an existing variable of the same name in a parent scope).

func (state *Runtime) LetGlobal(name string, val interface{})

LetGlobal sets or initialises a variable in the top-most template scope.

Resolve calls resolve() and panics if there is an error.

Resolve calls resolve() and ignores any errors, meaning it may return a zero reflect.Value.

Set sets an existing variable in the template scope it lives in.

func (state *Runtime) SetOrLet(name string, val interface{})

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).

func (st *Runtime) YieldBlock(name string, context interface{})

YieldBlock yields a block in the current context, will panic if the context is not available

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).

Set is responsible to load, parse and cache templates. Every Jet template is associated with a Set.

func NewSet(loader Loader, opts ...Option) *Set

NewSet returns a new Set relying on loader. NewSet panics if a nil Loader is passed.

func (s *Set) AddGlobal(key string, i interface{}) *Set

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.

func (s *Set) AddGlobalFunc(key string, fn Func) *Set

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.

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:

  1. catalog/products.list
  2. catalog/products.list.html.jet
  3. 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 (s *Set) LookupGlobal(key string) (val interface{}, found bool)

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.

func (s *Set) Parse(templatePath, contents string) (template *Template, err error)

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.

type SetNode struct {
	NodeBase
	Let                bool
	IndexExprGetLookup bool
	Left               []Expression
	Right              []Expression
}

SetNode represents a set action, ident( ',' ident)* '=' expression ( ',' expression )*

type SliceExprNode struct {
	NodeBase
	Base     Expression
	Index    Expression
	EndIndex Expression
}

StringNode holds a string constant. The value has been "unquoted".

Template is the representation of a single parsed template.

func (t *Template) Execute(w io.Writer, variables VarMap, data interface{}) (err error)

Execute executes the template into w.

func (t *Template) String() (template string)
type TernaryExprNode struct {
	NodeBase
	Boolean, Left, Right Expression
}

TernaryExprNod represents a ternary expression, ex: expression '?' expression ':' expression

type TextNode struct {
	NodeBase
	Text []byte
}

TextNode holds plain text.

type TryNode struct {
	NodeBase
	List  *ListNode
	Catch *catchNode
}
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 (scope VarMap) Set(name string, v interface{}) VarMap
func (scope VarMap) SetFunc(name string, v Func) VarMap
func (scope VarMap) SetWriter(name string, v SafeWriter) VarMap
func (scope VarMap) SortedKeys() []string

SortedKeys returns a sorted slice of VarMap keys

type YieldNode struct {
	NodeBase          
	Name       string 
	Parameters *BlockParameterList
	Expression Expression 
	Content    *ListNode
	IsContent  bool
}

YieldNode represents a {{yield}} action