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 ¶
- Variables
- func CompareObjects(a, b Object) (int, bool)
- func GetObjectLen(obj Object) int
- func GetObjectTruth(obj Object) bool
- func IterateObject(obj Object) iter.Seq[Value]
- func ReverseIterateObject(obj Object) iter.Seq[Value]
- type Callable
- type CallableObject
- type ItemGetter
- type Iterable
- type IterableObject
- type Iterator
- type LenGetter
- type MapGetter
- type MapObject
- type MethodCallable
- type MutableObject
- type Object
- type ObjectRepr
- type ObjectWithCmp
- type ObjectWithLen
- type ObjectWithRepr
- type ObjectWithString
- type ObjectWithTruth
- type PullIterator
- type ReversibleObject
- type SeqObject
- type State
- type UndefinedBehavior
- type Value
- func False() Value
- func FromAny(v any) Value
- func FromBigInt(v *big.Int) Value
- func FromBool(v bool) Value
- func FromBytes(v []byte) Value
- func FromCallable(c Callable) Value
- func FromFloat(v float64) Value
- func FromInt(v int64) Value
- func FromIterator(iter *Iterator) Value
- func FromMap(v map[string]Value) Value
- func FromObject(o Object) Value
- func FromSafeString(v string) Value
- func FromSlice(v []Value) Value
- func FromString(v string) Value
- func MakeIterable(maker func() iter.Seq[Value]) Value
- func MakeIterableFromSlice(maker func() []Value) Value
- func MakeObjectMap(enumerate func() iter.Seq[Value], getAttr func(key Value) Value) Value
- func MakeOneShotIterator(seq iter.Seq[Value]) Value
- func MergeMaps(sources ...Value) Value
- func None() Value
- func SilentUndefined() Value
- func True() Value
- func Undefined() Value
- func (v Value) Add(other Value) (Value, error)
- func (v Value) AsBool() (bool, bool)
- func (v Value) AsCallable() (Callable, bool)
- func (v Value) AsFloat() (float64, bool)
- func (v Value) AsInt() (int64, bool)
- func (v Value) AsMap() (map[string]Value, bool)
- func (v Value) AsMutableObject() (MutableObject, bool)
- func (v Value) AsObject() (Object, bool)
- func (v Value) AsSlice() ([]Value, bool)
- func (v Value) AsString() (string, bool)
- func (v Value) Clone() Value
- func (v Value) Compare(other Value) (int, bool)
- func (v Value) Concat(other Value) Value
- func (v Value) Contains(other Value) bool
- func (v Value) Div(other Value) (Value, error)
- func (v Value) Equal(other Value) bool
- func (v Value) FloorDiv(other Value) (Value, error)
- func (v Value) GetAttr(name string) Value
- func (v Value) GetItem(key Value) Value
- func (v Value) IsActualFloat() bool
- func (v Value) IsActualInt() bool
- func (v Value) IsCallable() bool
- func (v Value) IsNone() bool
- func (v Value) IsSafe() bool
- func (v Value) IsSilentUndefined() bool
- func (v Value) IsTrue() bool
- func (v Value) IsUndefined() bool
- func (v Value) Iter() []Value
- func (v Value) Kind() ValueKind
- func (v Value) Len() (int, bool)
- func (v Value) Mul(other Value) (Value, error)
- func (v Value) Neg() (Value, error)
- func (v Value) Pow(other Value) (Value, error)
- func (v Value) Raw() any
- func (v Value) Rem(other Value) (Value, error)
- func (v Value) Repr() string
- func (v Value) SameAs(other Value) bool
- func (v Value) String() string
- func (v Value) Sub(other Value) (Value, error)
- type ValueKind
Constants ¶
This section is empty.
Variables ¶
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 ¶
CompareObjects compares two objects using ObjectWithCmp if available. Returns (cmp, ok) where ok is false if objects are incomparable.
func GetObjectLen ¶
GetObjectLen returns the length of an object, or -1 if unknown.
func GetObjectTruth ¶
GetObjectTruth returns the truthiness of an object.
func IterateObject ¶
IterateObject returns an iterator over an object's values. Returns nil if the object is not iterable.
func ReverseIterateObject ¶
ReverseIterateObject returns a reverse iterator over an object's values. Returns nil if the object cannot be reverse-iterated.
Priority:
- ReversibleObject.ReverseIterate() if implemented
- SeqObject iterated in reverse (index n-1 to 0)
- 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 ¶
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 ¶
NewIterator creates a new iterator from items.
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 ¶
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 ¶
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 ¶
FromBool creates a Value from a boolean.
Example usage:
isActive := FromBool(true)
// In template: {% if isActive %}...{% endif %}
func FromBytes ¶
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 ¶
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 ¶
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 ¶
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 ¶
FromIterator creates a Value from an Iterator.
func FromMap ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 }} -> <b>Bold</b>
func MakeIterable ¶
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 ¶
MakeIterableFromSlice creates an iterable that yields values from a slice. The slice function is called each time to get fresh values.
func MakeObjectMap ¶
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 ¶
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 ¶
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) AsCallable ¶
AsCallable returns the Callable if this value is callable. This returns true for both Callable and CallableObject implementations.
func (Value) AsMutableObject ¶
func (v Value) AsMutableObject() (MutableObject, bool)
AsMutableObject returns the MutableObject if this value wraps one.
func (Value) Compare ¶
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) IsActualFloat ¶
IsActualFloat returns true if the value is stored as a float64.
func (Value) IsActualInt ¶
IsActualInt returns true if the value is stored as an integer (not a float). This distinguishes 42 from 42.0.
func (Value) IsCallable ¶
IsCallable returns true if this value is callable.
func (Value) IsSilentUndefined ¶ added in v2.16.0
IsSilentUndefined returns true if the value is an undefined value that should not trigger strict undefined errors.
func (Value) IsUndefined ¶
IsUndefined returns true if the value is undefined.
func (Value) SameAs ¶
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.
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 )