value

package
v2.17.1 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Overview

Package value provides a dynamic value type for the template engine.

The value package implements MiniJinja's dynamic type system, which allows templates to work with values of different types (strings, numbers, lists, maps, etc.) without compile-time type information.

Core Concepts

The Value type is the central type in this package. It can hold any Go value and provides methods for type checking, conversion, and operations. Values can be created from Go primitives using constructor functions like FromInt, FromString, FromSlice, etc.

Type System

MiniJinja supports the following value kinds:

  • Undefined: Represents a missing or undefined value
  • None: Represents null/nil
  • Bool: Boolean true/false
  • Number: Integers and floating-point numbers
  • String: UTF-8 text strings (safe or unsafe for auto-escaping)
  • Bytes: Binary data
  • Seq: Ordered sequences (arrays/slices)
  • Map: Key-value mappings (dictionaries/objects)
  • Iterable: Lazy iterators
  • Callable: Functions and macros
  • Plain: Custom objects with attribute access

Example Usage

// Create values from Go types
name := value.FromString("World")
count := value.FromInt(42)
items := value.FromSlice([]value.Value{
    value.FromString("apple"),
    value.FromString("banana"),
})

// Create a map/dict value
context := value.FromMap(map[string]value.Value{
    "name":  name,
    "count": count,
    "items": items,
})

// Type checking
if name.Kind() == value.KindString {
    fmt.Println("It's a string!")
}

// Conversion
if s, ok := name.AsString(); ok {
    fmt.Println("String value:", s)
}

Index

Constants

This section is empty.

Variables

View Source
var ErrUnknownMethod = errors.New("unknown method")

ErrUnknownMethod is returned by MethodCallable.CallMethod when the method is not known. This signals the engine to fall back to GetAttr + call.

Functions

func CompareObjects

func CompareObjects(a, b Object) (int, bool)

CompareObjects compares two objects using ObjectWithCmp if available. Returns (cmp, ok) where ok is false if objects are incomparable.

func GetObjectLen

func GetObjectLen(obj Object) int

GetObjectLen returns the length of an object, or -1 if unknown.

func GetObjectTruth

func GetObjectTruth(obj Object) bool

GetObjectTruth returns the truthiness of an object.

func IterateObject

func IterateObject(obj Object) iter.Seq[Value]

IterateObject returns an iterator over an object's values. Returns nil if the object is not iterable.

func ReverseIterateObject

func ReverseIterateObject(obj Object) iter.Seq[Value]

ReverseIterateObject returns a reverse iterator over an object's values. Returns nil if the object cannot be reverse-iterated.

Priority:

  1. ReversibleObject.ReverseIterate() if implemented
  2. SeqObject iterated in reverse (index n-1 to 0)
  3. nil (caller should collect and reverse)

Types

type Callable

type Callable interface {
	// Call invokes the callable with positional and keyword arguments.
	//
	// The state provides access to the template rendering context.
	// The args slice contains positional arguments in order.
	// The kwargs map contains keyword arguments by name.
	//
	// Returns the result value and any error that occurred.
	Call(state State, args []Value, kwargs map[string]Value) (Value, error)
}

Callable is an interface for callable objects like functions and macros.

Types that implement Callable can be invoked from templates using the call syntax: {{ my_function(arg1, arg2) }} or {{ my_macro(key=value) }}.

Example implementation:

type myCallable struct{}

func (m *myCallable) Call(state State, args []Value, kwargs map[string]Value) (Value, error) {
    // Process positional arguments
    if len(args) > 0 {
        fmt.Println("First arg:", args[0].String())
    }
    // Process keyword arguments
    if name, ok := kwargs["name"]; ok {
        fmt.Println("Name:", name.String())
    }
    return FromString("result"), nil
}

type CallableObject

type CallableObject interface {
	Object
	// ObjectCall invokes the object itself with the given arguments.
	ObjectCall(state State, args []Value, kwargs map[string]Value) (Value, error)
}

CallableObject is an object that can be called like a function. This is for objects that are themselves callable (not their methods).

Example: cycler = make_cycler("a", "b"); cycler() returns next value

type ItemGetter

type ItemGetter interface {
	GetItem(key Value) Value
}

ItemGetter is an interface for objects that support item access.

type Iterable

type Iterable interface {
	Iter() []Value
}

Iterable is an interface for objects that can be iterated.

type IterableObject

type IterableObject interface {
	Object
	// Iterate returns an iterator over the object's values.
	// Called each time iteration is needed (allows multiple iterations).
	// Return nil to indicate the object is not iterable.
	Iterate() iter.Seq[Value]
}

IterableObject can provide a custom iterator. This takes precedence over SeqObject/MapObject for iteration.

type Iterator

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

Iterator represents a lazy iterator value. Unlike sequences, iterators are consumed when iterated and don't have a length.

func NewIterator

func NewIterator(name string, items []Value) *Iterator

NewIterator creates a new iterator from items.

func (*Iterator) Items

func (i *Iterator) Items() []Value

Items returns the iterator's items (consuming it conceptually).

type LenGetter

type LenGetter interface {
	Len() (int, bool)
}

LenGetter is an interface for objects that have a length.

type MapGetter

type MapGetter interface {
	Map() map[string]Value
}

MapGetter is an interface for objects that expose mapping data.

type MapObject

type MapObject interface {
	Object
	// Keys returns the keys that this map contains.
	// Used for iteration, length calculation, and debug output.
	Keys() []string
}

MapObject is an object that behaves like a map with known keys. The engine iterates over Keys() and calls GetAttr for values.

type MethodCallable

type MethodCallable interface {
	Object
	// CallMethod invokes a method on the object.
	// Return ErrUnknownMethod to fall back to GetAttr(name) + call.
	CallMethod(state State, name string, args []Value, kwargs map[string]Value) (Value, error)
}

MethodCallable is an object that supports method calls. This allows `obj.method(args)` syntax to invoke methods on the object.

Example: magic.make_class("ul") calls the make_class method on magic

type MutableObject

type MutableObject interface {
	Object
	// SetAttr sets the value of the named attribute.
	SetAttr(name string, val Value)
}

MutableObject is an object that supports attribute assignment.

Types that implement MutableObject can have their attributes set from templates, typically via {% set obj.attr = value %} syntax.

This is primarily used for special objects like namespace() that need to support attribute assignment across scopes.

Example implementation:

type Namespace struct {
    attrs map[string]Value
}

func (n *Namespace) GetAttr(name string) Value {
    if v, ok := n.attrs[name]; ok {
        return v
    }
    return Undefined()
}

func (n *Namespace) SetAttr(name string, val Value) {
    n.attrs[name] = val
}

type Object

type Object interface {
	// GetAttr returns the value of the named attribute.
	//
	// If the attribute doesn't exist, returns Undefined().
	GetAttr(name string) Value
}

Object is an interface for custom objects with attribute access.

Types that implement Object can expose attributes that can be accessed from templates using dot notation: {{ obj.attribute_name }}.

This is useful for exposing Go structs and custom types to templates with specific attribute access semantics.

Example implementation:

type User struct {
    Username string
    Email    string
}

func (u *User) GetAttr(name string) Value {
    switch name {
    case "username":
        return FromString(u.Username)
    case "email":
        return FromString(u.Email)
    default:
        return Undefined()
    }
}

type ObjectRepr

type ObjectRepr int

ObjectRepr indicates the natural representation of an object.

const (
	// ObjectReprPlain is a plain object with no special iteration behavior.
	// This is the default for objects. They render as debug output and
	// are not iterable.
	ObjectReprPlain ObjectRepr = iota

	// ObjectReprMap indicates the object behaves like a map/dict.
	// Iteration yields keys, and values are accessed via GetAttr.
	ObjectReprMap

	// ObjectReprSeq indicates the object behaves like a sequence/array.
	// Iteration yields values from index 0 to SeqLen()-1.
	ObjectReprSeq

	// ObjectReprIterable indicates the object is a generic iterable.
	// It can be iterated but may not support indexing or have known length.
	ObjectReprIterable
)

func GetObjectRepr

func GetObjectRepr(obj Object) ObjectRepr

GetObjectRepr returns the representation type of an object.

func (ObjectRepr) String

func (r ObjectRepr) String() string

type ObjectWithCmp

type ObjectWithCmp interface {
	Object
	// ObjectCmp compares this object with another.
	// Returns (cmp, ok) where:
	//   - cmp < 0 means this < other
	//   - cmp == 0 means this == other
	//   - cmp > 0 means this > other
	//   - ok == false means the objects are incomparable
	ObjectCmp(other Object) (cmp int, ok bool)
}

ObjectWithCmp provides custom comparison for sorting. If not implemented, objects are compared by identity only.

Example:

type Thing struct { num int }

func (t *Thing) ObjectCmp(other Object) (int, bool) {
    if ot, ok := other.(*Thing); ok {
        return t.num - ot.num, true
    }
    return 0, false  // incomparable types
}

type ObjectWithLen

type ObjectWithLen interface {
	Object
	// ObjectLen returns the length of the object.
	// Return -1 if length is unknown.
	ObjectLen() int
}

ObjectWithLen provides explicit length for an object. If not implemented, length is derived from SeqObject or MapObject.

type ObjectWithRepr

type ObjectWithRepr interface {
	Object
	// ObjectRepr returns the natural representation of this object.
	ObjectRepr() ObjectRepr
}

ObjectWithRepr allows objects to specify their representation type. If not implemented, defaults to ObjectReprPlain.

type ObjectWithString

type ObjectWithString interface {
	Object
	// ObjectString returns the string representation of this object.
	ObjectString() string
}

ObjectWithString provides custom string representation. If not implemented, uses default formatting based on ObjectRepr.

type ObjectWithTruth

type ObjectWithTruth interface {
	Object
	// ObjectIsTrue returns whether this object is considered "true".
	ObjectIsTrue() bool
}

ObjectWithTruth provides custom truthiness for an object. If not implemented, truthiness is based on length (empty = false).

type PullIterator

type PullIterator interface {
	// PullNext returns the next item and whether there are more items.
	// Returns (value, true) for the next item, or (undefined, false) when exhausted.
	PullNext() (Value, bool)

	// PullDone returns true if the iterator is exhausted.
	PullDone() bool
}

PullIterator is an interface for pull-based iteration. This is used for one-shot iterators that need to preserve items across partial iterations (e.g., when a loop uses break).

Unlike regular iterables that are collected into slices, PullIterators allow item-by-item consumption with the ability to stop and resume.

type ReversibleObject

type ReversibleObject interface {
	Object
	// ReverseIterate returns an iterator that yields items in reverse order.
	// Return nil to fall back to collect-and-reverse behavior.
	ReverseIterate() iter.Seq[Value]
}

ReversibleObject can provide efficient reverse iteration. If not implemented, reverse() will collect and reverse the items.

This is useful for sequences that can be efficiently iterated in reverse without collecting all items first.

type SeqObject

type SeqObject interface {
	Object
	// SeqLen returns the length of the sequence.
	SeqLen() int
	// SeqItem returns the item at index (0-based).
	// Returns Undefined() if index is out of bounds.
	SeqItem(index int) Value
}

SeqObject is an object that behaves like a sequence. Implement this along with ObjectWithRepr returning ObjectReprSeq.

type State

type State interface {
	// Context returns the Go context for this render operation.
	Context() context.Context

	// Lookup looks up a variable by name in the current scope.
	Lookup(name string) Value

	// Name returns the name of the template being rendered.
	Name() string
}

State is the interface that the template engine's state must implement. This allows objects to access template state without circular dependencies.

type UndefinedBehavior added in v2.16.0

type UndefinedBehavior int

UndefinedBehavior determines how undefined values are handled at runtime.

This mirrors the behavior of MiniJinja's Rust implementation and provides several modes that control how undefined values interact with printing, iteration, attribute access, and truthiness checks.

const (
	// UndefinedLenient allows undefined values to be used in templates.
	// They render as empty strings, iterate as empty sequences, and are
	// considered false in boolean contexts.
	UndefinedLenient UndefinedBehavior = iota

	// UndefinedChainable allows chaining attribute/item access on undefined
	// values without erroring. Missing attributes on undefined remain undefined.
	UndefinedChainable

	// UndefinedSemiStrict behaves like strict undefined values for printing and
	// iteration, but allows undefined values to be used in boolean contexts.
	UndefinedSemiStrict

	// UndefinedStrict causes errors whenever undefined values are used in
	// printing, iteration, or boolean contexts.
	UndefinedStrict
)

type Value

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

Value represents a dynamically typed value in the template engine.

Value is the core type used throughout MiniJinja for representing template data. It can hold any Go value and provides methods for type checking, conversion, and operations.

Values are immutable for primitive types (strings, numbers, booleans) but sequences and maps are referenced, meaning modifications to the underlying Go slice or map will be visible through the Value.

Creating Values

Values are typically created using constructor functions:

str := FromString("hello")
num := FromInt(42)
list := FromSlice([]Value{str, num})
dict := FromMap(map[string]Value{"key": str})

Go values can also be automatically converted using FromAny:

val := FromAny(map[string]interface{}{
    "name": "Alice",
    "age": 30,
})

Type Checking

Use the Kind() method to check the type:

if val.Kind() == KindString {
    // It's a string
}

Or use type-specific checking methods:

if val.IsUndefined() { /* ... */ }
if val.IsTrue() { /* ... */ }

Type Conversion

Use As* methods to convert to specific types:

if s, ok := val.AsString(); ok {
    fmt.Println("String value:", s)
}
if i, ok := val.AsInt(); ok {
    fmt.Println("Integer value:", i)
}

Operations

Values support various operations defined in ops.go:

result, err := val1.Add(val2)  // arithmetic
cmp, ok := val1.Compare(val2)  // comparison
contains := val.Contains(item) // containment

func False

func False() Value

False returns the boolean false value.

This is a convenience function equivalent to FromBool(false).

func FromAny

func FromAny(v any) Value

FromAny creates a Value from any Go value using reflection.

FromAny automatically converts Go types to their corresponding Value types:

  • nil -> None()
  • bool -> FromBool()
  • int types -> FromInt()
  • uint types -> FromInt()
  • float types -> FromFloat()
  • string -> FromString()
  • []byte -> FromBytes()
  • slices/arrays -> FromSlice() (recursively)
  • maps -> FromMap() (recursively)
  • structs -> FromMap() (using exported fields and json tags)
  • pointers/interfaces -> dereference and convert

This is the most convenient way to convert Go data to Values, but it uses reflection and may be slower than using specific constructors.

Example usage:

data := FromAny(map[string]interface{}{
    "name": "Alice",
    "age":  30,
    "tags": []string{"admin", "user"},
})
// Equivalent to:
// FromMap(map[string]Value{
//     "name": FromString("Alice"),
//     "age": FromInt(30),
//     "tags": FromSlice([]Value{
//         FromString("admin"),
//         FromString("user"),
//     }),
// })

func FromBigInt

func FromBigInt(v *big.Int) Value

FromBigInt creates a Value from a big.Int for arbitrary-precision integers.

Big integers are used when values exceed the range of int64. They support the same arithmetic operations as regular integers.

Example usage:

large := new(big.Int)
large.SetString("123456789012345678901234567890", 10)
val := FromBigInt(large)
// In template: {{ val + 1 }}

func FromBool

func FromBool(v bool) Value

FromBool creates a Value from a boolean.

Example usage:

isActive := FromBool(true)
// In template: {% if isActive %}...{% endif %}

func FromBytes

func FromBytes(v []byte) Value

FromBytes creates a Value from a byte slice.

Byte values represent binary data. They can be used for non-text content and are distinct from strings (which are UTF-8 text).

Example usage:

data := FromBytes([]byte{0x48, 0x65, 0x6c, 0x6c, 0x6f})
// In template: {{ data }}  -> Hello

func FromCallable

func FromCallable(c Callable) Value

FromCallable creates a Value from a Callable.

Callables can be invoked from templates using function call syntax. This is useful for exposing custom functions to templates.

Example usage:

type MyFunc struct{}
func (f *MyFunc) Call(args []Value, kwargs map[string]Value) (Value, error) {
    return FromString("Hello!"), nil
}

fn := FromCallable(&MyFunc{})
context := FromMap(map[string]Value{"greet": fn})
// In template: {{ greet() }}  -> Hello!

func FromFloat

func FromFloat(v float64) Value

FromFloat creates a Value from a float64.

Floating-point values support arithmetic operations. Special values like infinity and NaN are handled according to Go's float64 semantics.

Example usage:

price := FromFloat(19.99)
// In template: {{ price * 1.2 }}  -> 23.988

func FromInt

func FromInt(v int64) Value

FromInt creates a Value from an int64.

Integer values support arithmetic operations and can be compared.

Example usage:

count := FromInt(42)
// In template: {{ count + 1 }}  -> 43

func FromIterator

func FromIterator(iter *Iterator) Value

FromIterator creates a Value from an Iterator.

func FromMap

func FromMap(v map[string]Value) Value

FromMap creates a Value from a map of string to Value.

Maps represent key-value associations (dictionaries/objects) that can be accessed using dot notation or bracket notation in templates. They correspond to objects in JSON and dicts in Python.

Example usage:

user := FromMap(map[string]Value{
    "name":  FromString("Alice"),
    "age":   FromInt(30),
    "email": FromString("[email protected]"),
})
// In template: {{ user.name }}  -> Alice
// In template: {{ user["age"] }}  -> 30
// In template: {% for key in user %}{{ key }}{% endfor %}

func FromObject

func FromObject(o Object) Value

FromObject creates a Value from an Object.

Objects expose attributes that can be accessed from templates using dot notation. This is useful for exposing custom types with specific attribute access semantics.

Example usage:

type User struct {
    Name string
    Age  int
}

func (u *User) GetAttr(name string) Value {
    switch name {
    case "name": return FromString(u.Name)
    case "age": return FromInt(int64(u.Age))
    default: return Undefined()
    }
}

user := &User{Name: "Alice", Age: 30}
val := FromObject(user)
// In template: {{ user.name }}  -> Alice

func FromSafeString

func FromSafeString(v string) Value

FromSafeString creates a Value from a safe (pre-escaped) string.

Safe strings are marked as already escaped and will not be escaped again by auto-escaping. This is useful when you want to include HTML or other markup that should be rendered as-is.

Example usage:

html := FromSafeString("<b>Bold</b>")
// In template with escaping: {{ html }}  -> <b>Bold</b>

Use this with caution - ensure the string is actually safe to prevent XSS.

func FromSlice

func FromSlice(v []Value) Value

FromSlice creates a Value from a slice of Values.

Slices represent ordered sequences (arrays/lists) that can be iterated over and indexed by position. They correspond to arrays in JSON and lists in Python.

Example usage:

items := FromSlice([]Value{
    FromString("apple"),
    FromString("banana"),
    FromString("cherry"),
})
// In template: {% for item in items %}{{ item }}{% endfor %}
// In template: {{ items[0] }}  -> apple
// In template: {{ items|length }}  -> 3

func FromString

func FromString(v string) Value

FromString creates a Value from a string.

String values are not marked as safe and will be escaped by auto-escaping if enabled. For pre-escaped HTML, use FromSafeString instead.

Example usage:

name := FromString("Alice")
// In template: {{ name }}  -> Alice
html := FromString("<b>Bold</b>")
// In template with escaping: {{ html }}  -> &lt;b&gt;Bold&lt;/b&gt;

func MakeIterable

func MakeIterable(maker func() iter.Seq[Value]) Value

MakeIterable creates a lazy iterable value from a maker function. The maker is called each time iteration is needed, allowing multiple iterations.

Example:

val := MakeIterable(func() iter.Seq[Value] {
    return func(yield func(Value) bool) {
        for i := 0; i < 10; i++ {
            if !yield(FromInt(int64(i))) {
                return
            }
        }
    }
})

func MakeIterableFromSlice

func MakeIterableFromSlice(maker func() []Value) Value

MakeIterableFromSlice creates an iterable that yields values from a slice. The slice function is called each time to get fresh values.

func MakeObjectMap

func MakeObjectMap(enumerate func() iter.Seq[Value], getAttr func(key Value) Value) Value

MakeObjectMap creates a map-like value that projects onto callbacks.

Parameters:

  • enumerate: returns an iterator over the map's keys
  • getAttr: returns the value for a given key

Example (projecting a Go map as a Value):

attrs := map[string]string{"id": "link-1", "class": "links"}
val := MakeObjectMap(
    func() iter.Seq[Value] {
        return func(yield func(Value) bool) {
            for k := range attrs {
                if !yield(FromString(k)) {
                    return
                }
            }
        }
    },
    func(key Value) Value {
        if s, ok := key.AsString(); ok {
            if v, exists := attrs[s]; exists {
                return FromString(v)
            }
        }
        return Undefined()
    },
)

func MakeOneShotIterator

func MakeOneShotIterator(seq iter.Seq[Value]) Value

MakeOneShotIterator creates an iterator that can only be consumed once.

Unlike MakeIterable, a one-shot iterator:

  • Can only be fully iterated once
  • Has no known length (loop.length is undefined)
  • Renders as "<iterator>"
  • After consumption, subsequent iterations yield nothing

If iteration is stopped early (e.g., with break), the remaining items are preserved for the next iteration attempt.

Example:

val := MakeOneShotIterator(func(yield func(Value) bool) {
    for i := 0; i < 10; i++ {
        if !yield(FromInt(int64(i))) {
            return
        }
    }
})

// First iteration: yields 0, 1, 2, ..., 9
// Second iteration: yields nothing

func MergeMaps

func MergeMaps(sources ...Value) Value

MergeMaps merges multiple map-like values into a single lazy map object.

Later values override earlier ones when keys overlap. Non-map values are ignored for enumeration, but attribute lookups are forwarded to any objects that implement map-like access.

This mirrors the behavior of MiniJinja's context merging in Rust.

func None

func None() Value

None returns the none/null value.

None represents an explicit null value, equivalent to null in JSON, nil in Go, or None in Python.

Example usage:

context := FromMap(map[string]Value{
    "name": FromString("Alice"),
    "age":  None(),  // explicitly null
})

func SilentUndefined added in v2.16.0

func SilentUndefined() Value

SilentUndefined returns an undefined value that does not trigger strict undefined errors when rendered or evaluated for truthiness.

This is used internally for expressions like "a if cond" where the false branch is omitted.

func True

func True() Value

True returns the boolean true value.

This is a convenience function equivalent to FromBool(true).

func Undefined

func Undefined() Value

Undefined returns the undefined value.

Undefined represents a missing or non-existent value. In templates, undefined values typically render as empty strings unless strict undefined behavior is enabled.

Example usage:

// Return undefined from a custom object
func (obj *MyObject) GetAttr(name string) Value {
    if name == "existing" {
        return FromString("value")
    }
    return Undefined()  // attribute doesn't exist
}

func (Value) Add

func (v Value) Add(other Value) (Value, error)

Add performs addition or string concatenation.

func (Value) AsBool

func (v Value) AsBool() (bool, bool)

AsBool returns the boolean value if it is one.

func (Value) AsCallable

func (v Value) AsCallable() (Callable, bool)

AsCallable returns the Callable if this value is callable. This returns true for both Callable and CallableObject implementations.

func (Value) AsFloat

func (v Value) AsFloat() (float64, bool)

AsFloat returns the float value if it is numeric.

func (Value) AsInt

func (v Value) AsInt() (int64, bool)

AsInt returns the integer value if it is one.

func (Value) AsMap

func (v Value) AsMap() (map[string]Value, bool)

AsMap returns the map if it is one.

func (Value) AsMutableObject

func (v Value) AsMutableObject() (MutableObject, bool)

AsMutableObject returns the MutableObject if this value wraps one.

func (Value) AsObject

func (v Value) AsObject() (Object, bool)

AsObject returns the Object if this value wraps one.

func (Value) AsSlice

func (v Value) AsSlice() ([]Value, bool)

AsSlice returns the slice if it is one.

func (Value) AsString

func (v Value) AsString() (string, bool)

AsString returns the string value if it is one.

func (Value) Clone

func (v Value) Clone() Value

Clone creates a copy of the value.

func (Value) Compare

func (v Value) Compare(other Value) (int, bool)

Compare returns -1 if v < other, 0 if equal, 1 if v > other. Unlike Equal, Compare uses kind ordering first (like Rust's Ord).

func (Value) Concat

func (v Value) Concat(other Value) Value

Concat performs the tilde (~) string concatenation.

func (Value) Contains

func (v Value) Contains(other Value) bool

Contains checks if v contains other.

func (Value) Div

func (v Value) Div(other Value) (Value, error)

Div performs division.

func (Value) Equal

func (v Value) Equal(other Value) bool

Equal returns true if two values are equal.

func (Value) FloorDiv

func (v Value) FloorDiv(other Value) (Value, error)

FloorDiv performs floor division.

func (Value) GetAttr

func (v Value) GetAttr(name string) Value

GetAttr gets an attribute by name.

func (Value) GetItem

func (v Value) GetItem(key Value) Value

GetItem gets an item by key (string or integer index).

func (Value) IsActualFloat

func (v Value) IsActualFloat() bool

IsActualFloat returns true if the value is stored as a float64.

func (Value) IsActualInt

func (v Value) IsActualInt() bool

IsActualInt returns true if the value is stored as an integer (not a float). This distinguishes 42 from 42.0.

func (Value) IsCallable

func (v Value) IsCallable() bool

IsCallable returns true if this value is callable.

func (Value) IsNone

func (v Value) IsNone() bool

IsNone returns true if the value is none.

func (Value) IsSafe

func (v Value) IsSafe() bool

IsSafe returns true if this is a safe string.

func (Value) IsSilentUndefined added in v2.16.0

func (v Value) IsSilentUndefined() bool

IsSilentUndefined returns true if the value is an undefined value that should not trigger strict undefined errors.

func (Value) IsTrue

func (v Value) IsTrue() bool

IsTrue returns the truthiness of the value.

func (Value) IsUndefined

func (v Value) IsUndefined() bool

IsUndefined returns true if the value is undefined.

func (Value) Iter

func (v Value) Iter() []Value

Iter returns an iterator over the value's items.

func (Value) Kind

func (v Value) Kind() ValueKind

Kind returns the kind of value.

func (Value) Len

func (v Value) Len() (int, bool)

Len returns the length of the value if it has one.

func (Value) Mul

func (v Value) Mul(other Value) (Value, error)

Mul performs multiplication.

func (Value) Neg

func (v Value) Neg() (Value, error)

Neg performs unary negation.

func (Value) Pow

func (v Value) Pow(other Value) (Value, error)

Pow performs exponentiation.

func (Value) Raw

func (v Value) Raw() any

Raw returns the underlying Go value.

func (Value) Rem

func (v Value) Rem(other Value) (Value, error)

Rem performs modulo operation.

func (Value) Repr

func (v Value) Repr() string

Repr returns a debug representation of the value.

func (Value) SameAs

func (v Value) SameAs(other Value) bool

SameAs checks if two values are identical (stricter than equality). For objects and sequences/maps, checks if they are the same instance. For primitives, checks type match and value equality.

func (Value) String

func (v Value) String() string

String returns a string representation of the value.

func (Value) Sub

func (v Value) Sub(other Value) (Value, error)

Sub performs subtraction.

type ValueKind

type ValueKind int

ValueKind describes the type of a Value.

ValueKind is used to determine what type of data a Value contains without needing to perform type assertions. This allows for efficient type checking in templates and filters.

Example usage:

val := FromString("hello")
if val.Kind() == KindString {
    s, _ := val.AsString()
    fmt.Println("String:", s)
}
const (
	// KindUndefined represents an undefined or missing value.
	//
	// Undefined values are returned when accessing non-existent variables,
	// attributes, or items. In templates, undefined values typically render
	// as empty strings unless strict undefined behavior is enabled.
	KindUndefined ValueKind = iota

	// KindNone represents a null/nil value.
	//
	// None is the equivalent of null in JSON, nil in Go, or None in Python.
	// It's used to explicitly represent the absence of a value.
	KindNone

	// KindBool represents a boolean value (true or false).
	//
	// Boolean values are used in conditionals and logic operations.
	KindBool

	// KindNumber represents a numeric value (integer or floating-point).
	//
	// Numbers can be either int64 or float64 internally, and support
	// arithmetic operations.
	KindNumber

	// KindString represents a text string.
	//
	// Strings can be either safe (pre-escaped) or unsafe (need escaping).
	// Safe strings are marked internally and won't be escaped again by
	// auto-escaping.
	KindString

	// KindBytes represents binary data.
	//
	// Bytes are similar to strings but represent raw binary data rather
	// than UTF-8 text.
	KindBytes

	// KindSeq represents an ordered sequence (array/list).
	//
	// Sequences can be iterated over and indexed by integer position.
	KindSeq

	// KindMap represents a key-value mapping (dict/object).
	//
	// Maps associate string keys with values and can be accessed using
	// dot notation or bracket notation in templates.
	KindMap

	// KindIterable represents a lazy iterator.
	//
	// Iterables are special sequences that are consumed when iterated.
	// They may not have a known length and can only be iterated once.
	KindIterable

	// KindCallable represents a callable object (function/macro).
	//
	// Callables can be invoked with arguments from templates.
	KindCallable

	// KindPlain represents a custom object with attribute access.
	//
	// Plain objects implement the Object interface and expose attributes
	// that can be accessed from templates.
	KindPlain

	// KindInvalid represents an invalid or corrupt value.
	//
	// This is rarely encountered and typically indicates an internal error.
	KindInvalid
)

func (ValueKind) String

func (k ValueKind) String() string

Jump to

Keyboard shortcuts

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