exec

package
v2.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 28, 2026 License: MIT Imports: 22 Imported by: 30

Documentation

Overview

Package exec provides template execution support.

Index

Constants

This section is empty.

Variables

View Source
var TypeDict = reflect.TypeFor[Dict]()

Functions

func AnyArgument added in v2.1.0

func AnyArgument(output *any) func(*Value) error

func BoolArgument added in v2.1.2

func BoolArgument(output *bool) func(*Value) error

func CaseInsensitive

func CaseInsensitive(data sort.Interface) sort.Interface

CaseInsensitive returns the data sorted in a case insensitive way (if string).

func FloatArgument added in v2.1.3

func FloatArgument(output *float64) func(v *Value) error

func IntArgument added in v2.1.0

func IntArgument(output *int) func(v *Value) error

func KeywordArgument added in v2.1.0

func KeywordArgument(name string, defaultValue *Value, transmuters ...ArgumentTransmuter) *argument

func NumberArgument added in v2.1.3

func NumberArgument(output *float64) func(v *Value) error

func OrArgument added in v2.1.0

func OrArgument(transmuters ...ArgumentTransmuter) func(*Value) error

func PositionalArgument added in v2.1.0

func PositionalArgument(name string, fallback *Value, transmuters ...ArgumentTransmuter) *argument

func Self

func Self(r *Renderer) map[string]func() string

func StringArgument added in v2.1.0

func StringArgument(output *string) func(*Value) error

func StringEnumArgument added in v2.1.0

func StringEnumArgument(output *string, options []string) func(v *Value) error

func StringListArgument added in v2.1.0

func StringListArgument(output *[]string) func(*Value) error

Types

type ArgumentTransmuter added in v2.1.0

type ArgumentTransmuter func(*Value) error

type Context

type Context struct {
	// contains filtered or unexported fields
}

func EmptyContext

func EmptyContext() *Context

func NewContext

func NewContext(data map[string]any) *Context

func (*Context) Get

func (ctx *Context) Get(name string) (any, bool)

func (*Context) Has

func (ctx *Context) Has(name string) bool

func (*Context) Inherit

func (ctx *Context) Inherit() *Context

func (*Context) Set

func (ctx *Context) Set(name string, value any)

func (*Context) Update

func (ctx *Context) Update(other *Context) *Context

Update updates this context with the key/value pairs from a map.

type ControlStructure

type ControlStructure interface {
	nodes.ControlStructure
	Execute(*Renderer, *nodes.ControlStructureBlock) error
}

type ControlStructureSet

type ControlStructureSet struct {
	// contains filtered or unexported fields
}

func NewControlStructureSet added in v2.2.0

func NewControlStructureSet(statements map[string]parser.ControlStructureParser) *ControlStructureSet

func (*ControlStructureSet) Exists

func (c *ControlStructureSet) Exists(name string) bool

Exists returns true if the given test is already registered

func (*ControlStructureSet) Get added in v2.2.0

func (*ControlStructureSet) Register

func (c *ControlStructureSet) Register(name string, parser parser.ControlStructureParser) error

Register registers a new tag. You usually want to call this function in the tag's init() function: http://golang.org/doc/effective_go.html#init

func (*ControlStructureSet) Replace

Replace replaces an already registered tag with a new implementation. Use this function with caution since it allows you to change existing tag behaviour.

func (*ControlStructureSet) Update

type Dict

type Dict struct {
	Pairs []*Pair
}

func NewDict

func NewDict() *Dict

func (*Dict) Get

func (d *Dict) Get(key *Value) *Value

func (*Dict) Keys

func (d *Dict) Keys() ValuesList

func (*Dict) String

func (d *Dict) String() string

type Environment

type Environment struct {
	Filters           *FilterSet
	ControlStructures *ControlStructureSet
	Tests             *TestSet
	Context           *Context
	Methods           Methods
}

type ErrInvalidCall added in v2.1.3

type ErrInvalidCall error

type Evaluator

type Evaluator struct {
	Config      *config.Config
	Environment *Environment
	Loader      loaders.Loader
}

func (*Evaluator) Eval

func (e *Evaluator) Eval(node nodes.Expression) *Value

func (*Evaluator) EvalTest

func (e *Evaluator) EvalTest(expr *nodes.TestExpression) *Value

func (*Evaluator) EvaluateFiltered

func (e *Evaluator) EvaluateFiltered(expr *nodes.FilteredExpression) *Value

EvaluateFiltered evaluates a filtered expression

func (*Evaluator) ExecuteFilter

func (e *Evaluator) ExecuteFilter(fc *nodes.FilterCall, v *Value) *Value

ExecuteFilter executes a filter node

func (*Evaluator) ExecuteFilterByName

func (e *Evaluator) ExecuteFilterByName(name string, in *Value, params *VarArgs) *Value

ExecuteFilterByName executes a filter given its name

func (*Evaluator) ExecuteTest

func (e *Evaluator) ExecuteTest(tc *nodes.TestCall, v *Value) *Value

func (*Evaluator) ExecuteTestByName

func (e *Evaluator) ExecuteTestByName(name string, in *Value, params *VarArgs) *Value

type FilterFunction

type FilterFunction func(e *Evaluator, in *Value, params *VarArgs) *Value

FilterFunction is the type filter functions must fulfill

type FilterSet

type FilterSet struct {
	// contains filtered or unexported fields
}

func NewFilterSet added in v2.2.0

func NewFilterSet(filters map[string]FilterFunction) *FilterSet

func (*FilterSet) Exists

func (f *FilterSet) Exists(name string) bool

Exists returns true if the given filter is already registered

func (*FilterSet) Get added in v2.2.0

func (f *FilterSet) Get(name string) (FilterFunction, bool)

Get returns true and the named filter if it is already registered

func (*FilterSet) Register

func (f *FilterSet) Register(name string, fn FilterFunction) error

Register registers a new filter. If there's already a filter with the same name, Register will panic. You usually want to call this function in the filter's init() function: http://golang.org/doc/effective_go.html#init

func (*FilterSet) Replace

func (f *FilterSet) Replace(name string, fn FilterFunction) error

Replace replaces an already registered filter with a new implementation. Use this function with caution since it allows you to change existing filter behaviour.

func (*FilterSet) Update

func (f *FilterSet) Update(other *FilterSet) *FilterSet

type KwArg

type KwArg struct {
	Name    string
	Default any
}

type Macro

type Macro func(params *VarArgs) *Value

Macro is the type macro functions must fulfill

func MacroNodeToFunc

func MacroNodeToFunc(node *nodes.Macro, r *Renderer) (Macro, error)

type MacroSet

type MacroSet map[string]Macro

func (MacroSet) Exists

func (ms MacroSet) Exists(name string) bool

Exists returns true if the given filter is already registered

func (*MacroSet) Register

func (ms *MacroSet) Register(name string, fn Macro) error

Register registers a new filter. If there's already a filter with the same name, Register will panic. You usually want to call this function in the filter's init() function: http://golang.org/doc/effective_go.html#init

func (*MacroSet) Replace

func (ms *MacroSet) Replace(name string, fn Macro) error

Replace replaces an already registered filter with a new implementation. Use this function with caution since it allows you to change existing filter behaviour.

type Method added in v2.1.0

type Method[I any] func(self I, selfValue *Value, arguments *VarArgs) (any, error)

type MethodSet added in v2.1.0

type MethodSet[I any] struct {
	// contains filtered or unexported fields
}

func NewMethodSet added in v2.2.0

func NewMethodSet[I any](methods map[string]Method[I]) *MethodSet[I]

func (*MethodSet[I]) Exists added in v2.1.0

func (m *MethodSet[I]) Exists(name string) bool

func (*MethodSet[I]) Get added in v2.2.0

func (m *MethodSet[I]) Get(name string) (Method[I], bool)

type Methods added in v2.1.0

type Methods struct {
	Bool  *MethodSet[bool]
	Int   *MethodSet[int]
	Float *MethodSet[float64]
	Str   *MethodSet[string]
	Dict  *MethodSet[map[string]any]
	List  *MethodSet[[]any]
}

type Pair

type Pair struct {
	Key   *Value
	Value *Value
}

func (*Pair) String

func (p *Pair) String() string

type ReducedVarArgs

type ReducedVarArgs struct {
	*VarArgs
	// contains filtered or unexported fields
}

ReducedVarArgs represents python variadic arguments / keyword arguments but values are reduced (i.e. keyword arguments given as arguments are accessible by name)

func (*ReducedVarArgs) Error

func (r *ReducedVarArgs) Error() string

func (*ReducedVarArgs) IsError

func (r *ReducedVarArgs) IsError() bool

IsError returns true if there was an error on Expect call

type Renderer

type Renderer struct {
	Config      *config.Config
	Environment *Environment
	Loader      loaders.Loader
	Template    *Template
	RootNode    *nodes.Template
	Output      io.Writer
}

Renderer is a node visitor in charge of rendering

func NewRenderer

func NewRenderer(environment *Environment, wr io.Writer, config *config.Config, loader loaders.Loader, template *Template) *Renderer

NewRenderer initializes a new renderer

func (*Renderer) Eval

func (r *Renderer) Eval(node nodes.Expression) *Value

func (*Renderer) Evaluator

func (r *Renderer) Evaluator() *Evaluator

func (*Renderer) Execute

func (r *Renderer) Execute() error

func (*Renderer) ExecuteIfWrapper added in v2.3.4

func (r *Renderer) ExecuteIfWrapper(wrapper *nodes.Wrapper) error

ExecuteIfWrapper wraps the nodes.Wrapper execution logic and updates the parent context

func (*Renderer) ExecuteWrapper

func (r *Renderer) ExecuteWrapper(wrapper *nodes.Wrapper) error

ExecuteWrapper wraps the nodes.Wrapper execution logic

func (*Renderer) Inherit

func (r *Renderer) Inherit() *Renderer

Inherit creates a new sub renderer

func (*Renderer) Visit

func (r *Renderer) Visit(node nodes.Node) (nodes.Visitor, error)

Visit implements the nodes.Visitor interface

type Template

type Template struct {
	// contains filtered or unexported fields
}

func NewTemplate

func NewTemplate(identifier string, config *config.Config, loader loaders.Loader, environment *Environment) (*Template, error)

NewTemplate creates a gonja template instance that can be executed with a given context later on

func (*Template) Execute

func (t *Template) Execute(wr io.Writer, data *Context) error

Execute executes the template and returns the rendered content in the provided writer

func (*Template) ExecuteToBytes

func (t *Template) ExecuteToBytes(data *Context) ([]byte, error)

ExecuteToBytes executes the template and returns the rendered content as bytes

func (*Template) ExecuteToString

func (t *Template) ExecuteToString(data *Context) (string, error)

ExecuteToString executes the template and returns the rendered content as a string

func (*Template) Macros

func (t *Template) Macros() map[string]*nodes.Macro

Macros returns all macros available to the template

func (*Template) Root added in v2.6.0

func (t *Template) Root() *nodes.Template

Root returns the root node of the template

type TestFunction

type TestFunction any

TestFunction is the type test functions must fulfill is type TestFunction func(*Evaluator, *Value, *VarArgs) (bool, error) but we use an so as to support the legacy type type TestFunction func(*Context, *Value, *VarArgs) (bool, error) in a backwards compatible way

type TestSet

type TestSet struct {
	// contains filtered or unexported fields
}

TestSet maps test names to their TestFunction handler

func NewTestSet added in v2.2.0

func NewTestSet(tests map[string]TestFunction) *TestSet

func (*TestSet) Exists

func (t *TestSet) Exists(name string) bool

Exists returns true if the given test is already registered

func (*TestSet) Get added in v2.2.0

func (t *TestSet) Get(name string) (TestFunction, bool)

func (*TestSet) Register

func (t *TestSet) Register(name string, fn TestFunction) error

Register registers a new test. If there's already a test with the same name, RegisterTest will error out.

func (*TestSet) Replace

func (t *TestSet) Replace(name string, fn TestFunction) error

Replace replaces an already registered test with a new implementation. Use this function with caution since it allows you to change existing test behaviour.

func (*TestSet) Update

func (t *TestSet) Update(other *TestSet) *TestSet

type Value

type Value struct {
	Val  reflect.Value
	Safe bool // used to indicate whether a Value needs explicit escaping in the template
}

func AsSafeValue

func AsSafeValue(i any) *Value

AsSafeValue works like AsValue, but does not apply the 'escape' filter.

func AsValue

func AsValue(i any) *Value

AsValue converts any given Value to a gonja.Value. Usually being used within functions passed to a template through a Context or within filter functions.

Example:

AsValue("my string")

func ToValue

func ToValue(data any) *Value

func ValueError

func ValueError(err error) *Value

func (*Value) Bool

func (v *Value) Bool() bool

Bool returns the underlying value as a bool. If the value is not a bool, false will always be returned. If you're looking for true/false-evaluation of the underlying value, have a look at the IsTrue() function.

func (*Value) CanSlice

func (v *Value) CanSlice() bool

CanSlice checks whether the underlying value is of type array, slice or string. You normally would use CanSlice() before using the Slice() operation.

func (*Value) Contains

func (v *Value) Contains(other *Value) bool

Contains checks whether the underlying value (which must be of type struct, map, string, array or slice) contains of Value (e.g. to check whether a struct contains a specific field or a map contains a specific key).

Example:

AsValue("Hello, World!").Contains(AsValue("World")) == true

func (*Value) EqualValueTo

func (v *Value) EqualValueTo(other *Value) bool

EqualValueTo checks whether two values are equal.

func (*Value) Error

func (v *Value) Error() string

func (*Value) Escaped

func (v *Value) Escaped() string

Escaped returns the escaped version of String()

func (*Value) Float

func (v *Value) Float() float64

Float returns the underlying value as a float (converting the underlying value, if necessary). If it's not possible to convert the underlying value, it will return 0.0.

func (*Value) Get

func (v *Value) Get(key string) (*Value, bool)

func (*Value) GetAttribute

func (v *Value) GetAttribute(name string) (*Value, bool)

func (*Value) GetItem

func (v *Value) GetItem(key any) (*Value, bool)

func (*Value) Index

func (v *Value) Index(i int) *Value

Index gets the i-th item of an array, slice or string. Otherwise it will return nil.

func (*Value) Integer

func (v *Value) Integer() int

Integer returns the underlying value as an integer (converts the underlying value, if necessary). If it's not possible to convert the underlying value, it will return 0.

func (*Value) Interface

func (v *Value) Interface() any

Interface returns the underlying value.

func (*Value) IsBool

func (v *Value) IsBool() bool

IsBool checks whether the underlying value is a bool

func (*Value) IsCallable

func (v *Value) IsCallable() bool

func (*Value) IsDict

func (v *Value) IsDict() bool

func (*Value) IsError

func (v *Value) IsError() bool

func (*Value) IsFloat

func (v *Value) IsFloat() bool

IsFloat checks whether the underlying value is a float

func (*Value) IsInteger

func (v *Value) IsInteger() bool

IsInteger checks whether the underlying value is an integer

func (*Value) IsIterable

func (v *Value) IsIterable() bool

func (*Value) IsList

func (v *Value) IsList() bool

func (*Value) IsNil

func (v *Value) IsNil() bool

IsNil checks whether the underlying value is nil

func (*Value) IsNumber

func (v *Value) IsNumber() bool

IsNumber checks whether the underlying value is either an integer or a float.

func (*Value) IsString

func (v *Value) IsString() bool

IsString checks whether the underlying value is a string

func (*Value) IsTrue

func (v *Value) IsTrue() bool

IsTrue tries to evaluate the underlying value the Pythonic-way by returning true in one the following cases:

  • int != 0
  • uint != 0
  • float != 0.0
  • len(array/chan/map/slice/string) > 0
  • bool == true
  • underlying value is a struct

In any other case, IsTrue returns false.

func (*Value) Items

func (v *Value) Items() []*Pair

func (*Value) Iterate

func (v *Value) Iterate(fn func(idx, count int, key, value *Value) bool, empty func())

Iterate iterates over a map, array, slice or a string. It calls the function's first argument for every value with the following arguments:

idx      current 0-index
count    total amount of items
key      *Value for the key or item
value    *Value (only for maps, the respective value for a specific key)

If the underlying value has no items or is not one of the types above, the empty function (Iterate's second argument) will be called.

func (*Value) IterateOrder

func (v *Value) IterateOrder(fn func(idx, count int, key, value *Value) bool, empty func(), reverse bool, sorted bool, caseSensitive bool)

IterateOrder behaves like Value.Iterate, but can iterate through an array/slice/string in reverse. Does not affect the iteration through a map because maps don't have any particular order. However, you can force an order using the `sorted` keyword (and even use `reversed sorted`).

func (*Value) Keys

func (v *Value) Keys() ValuesList

func (*Value) Len

func (v *Value) Len() int

Len returns the length for an array, chan, map, slice or string. Otherwise it will return 0.

func (*Value) Negate

func (v *Value) Negate() *Value

Negate tries to negate the underlying value. It's mainly used for the NOT-operator and in conjunction with a call to return_value.IsTrue() afterwards.

Example:

AsValue(1).Negate().IsTrue() == false

func (*Value) Set

func (v *Value) Set(key *Value, value any) error

func (*Value) Slice

func (v *Value) Slice(i, j int) *Value

Slice slices an array, slice or string. Otherwise it will return an empty []int.

func (*Value) String

func (v *Value) String() string

String returns a string for the underlying value. If this value is not of type string, gonja tries to convert it. Currently the following types for underlying values are supported:

  1. string
  2. int/uint (any size)
  3. float (any precision)
  4. bool
  5. time.Time
  6. String() will be called on the underlying value if provided

nil values will lead to an empty string. For unsupported types, String will return to the type's name.

func (*Value) ToGoSimpleType

func (v *Value) ToGoSimpleType(allowInterfaceKeys bool) any

type ValuesList

type ValuesList []*Value

func (ValuesList) Contains

func (vl ValuesList) Contains(value *Value) bool

func (ValuesList) Len

func (vl ValuesList) Len() int

func (ValuesList) Less

func (vl ValuesList) Less(i, j int) bool

func (ValuesList) String

func (vl ValuesList) String() string

func (ValuesList) Swap

func (vl ValuesList) Swap(i, j int)

type VarArgs

type VarArgs struct {
	Args   []*Value
	KwArgs map[string]*Value
}

VarArgs represents pythonic variadic args/kwargs

func NewVarArgs

func NewVarArgs() *VarArgs

func (*VarArgs) Expect

func (va *VarArgs) Expect(arguments int, keywordArguments []*KwArg) *ReducedVarArgs

Expect validates VarArgs against an expected signature

func (*VarArgs) ExpectArgs

func (va *VarArgs) ExpectArgs(args int) *ReducedVarArgs

ExpectArgs ensures VarArgs receive only arguments

func (*VarArgs) ExpectKwArgs

func (va *VarArgs) ExpectKwArgs(kwargs []*KwArg) *ReducedVarArgs

ExpectKwArgs allow to specify expected KwArgs

func (*VarArgs) ExpectNothing

func (va *VarArgs) ExpectNothing() *ReducedVarArgs

ExpectNothing ensures VarArgs does not receive any argument

func (*VarArgs) First

func (va *VarArgs) First() *Value

First returns the first argument or nil as a Value

func (*VarArgs) GetKeywordArgument added in v2.1.0

func (va *VarArgs) GetKeywordArgument(key string, fallback any) *Value

GetKeywordArgument gets a keyword arguments with fallback on default value

func (*VarArgs) Take added in v2.1.0

func (va *VarArgs) Take(arguments ...*argument) error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL