pub struct Value(_);
Expand description
Represents a dynamically typed value in the template engine.
Implementations§
source§impl Value
impl Value
sourcepub const UNDEFINED: Value = _
pub const UNDEFINED: Value = _
The undefined value.
This constant exists because the undefined type does not exist in Rust and this is the only way to construct it.
sourcepub fn from_serializable<T: Serialize>(value: &T) -> Value
pub fn from_serializable<T: Serialize>(value: &T) -> Value
Creates a value from something that can be serialized.
This is the method that MiniJinja will generally use whenever a serializable
object is passed to one of the APIs that internally want to create a value.
For instance this is what context!
and
render
will use.
During serialization of the value, serializing_for_value
will return
true
which makes it possible to customize serialization for MiniJinja.
For more information see serializing_for_value
.
let val = Value::from_serializable(&vec![1, 2, 3]);
This method does not fail but it might return a value that is not valid. Such
values will when operated on fail in the template engine in most situations.
This for instance can happen if the underlying implementation of Serialize
fails. There are also cases where invalid objects are silently hidden in the
engine today. This is for instance the case for when keys are used in hash maps
that the engine cannot deal with. Invalid values are considered an implementation
detail. There is currently no API to validate a value.
If the deserialization
feature is enabled then the inverse of this method
is to use the Value
type as serializer. You can pass a value into the
deserialize
method of a type that supports
serde deserialization.
sourcepub fn from_safe_string(value: String) -> Value
pub fn from_safe_string(value: String) -> Value
Creates a value from a safe string.
A safe string is one that will bypass auto escaping. For instance if you
want to have the template engine render some HTML without the user having to
supply the |safe
filter, you can use a value of this type instead.
let val = Value::from_safe_string("<em>note</em>".into());
sourcepub fn from_object<T: Object>(value: T) -> Value
pub fn from_object<T: Object>(value: T) -> Value
Creates a value from a dynamic object.
For more information see Object
.
use std::fmt;
#[derive(Debug)]
struct Thing {
id: usize,
}
impl fmt::Display for Thing {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
impl Object for Thing {}
let val = Value::from_object(Thing { id: 42 });
Objects are internally reference counted. If you want to hold on to the
Arc
you can directly create the value from an arc’ed object:
use std::sync::Arc;
let val = Value::from(Arc::new(Thing { id: 42 }));
sourcepub fn from_seq_object<T: SeqObject + 'static>(value: T) -> Value
pub fn from_seq_object<T: SeqObject + 'static>(value: T) -> Value
sourcepub fn from_struct_object<T: StructObject + 'static>(value: T) -> Value
pub fn from_struct_object<T: StructObject + 'static>(value: T) -> Value
Creates a value from an owned StructObject
.
This is a simplified API for creating dynamic structs
without having to implement the entire Object
protocol.
sourcepub fn from_function<F, Rv, Args>(f: F) -> Valuewhere
F: Function<Rv, Args> + for<'a> Function<Rv, <Args as FunctionArgs<'a>>::Output>,
Rv: FunctionResult,
Args: for<'a> FunctionArgs<'a>,
pub fn from_function<F, Rv, Args>(f: F) -> Valuewhere F: Function<Rv, Args> + for<'a> Function<Rv, <Args as FunctionArgs<'a>>::Output>, Rv: FunctionResult, Args: for<'a> FunctionArgs<'a>,
Creates a callable value from a function.
let pow = Value::from_function(|a: u32| a * a);
sourcepub fn kind(&self) -> ValueKind
pub fn kind(&self) -> ValueKind
Returns the kind of the value.
This can be used to determine what’s in the value before trying to perform operations on it.
sourcepub fn is_undefined(&self) -> bool
pub fn is_undefined(&self) -> bool
Returns true
if this value is undefined.
sourcepub fn as_object(&self) -> Option<&dyn Object>
pub fn as_object(&self) -> Option<&dyn Object>
If the value is an object, it’s returned as Object
.
sourcepub fn as_seq(&self) -> Option<&dyn SeqObject>
pub fn as_seq(&self) -> Option<&dyn SeqObject>
If the value is a sequence it’s returned as SeqObject
.
sourcepub fn as_struct(&self) -> Option<&dyn StructObject>
pub fn as_struct(&self) -> Option<&dyn StructObject>
If the value is a struct, return it as StructObject
.
sourcepub fn len(&self) -> Option<usize>
pub fn len(&self) -> Option<usize>
Returns the length of the contained value.
Values without a length will return None
.
let seq = Value::from(vec![1, 2, 3, 4]);
assert_eq!(seq.len(), Some(4));
sourcepub fn get_attr(&self, key: &str) -> Result<Value, Error>
pub fn get_attr(&self, key: &str) -> Result<Value, Error>
Looks up an attribute by attribute name.
This this returns UNDEFINED
when an invalid key is
resolved. An error is returned when if the value does not contain an object
that has attributes.
let ctx = minijinja::context! {
foo => "Foo"
};
let value = ctx.get_attr("foo")?;
assert_eq!(value.to_string(), "Foo");
sourcepub fn get_item_by_index(&self, idx: usize) -> Result<Value, Error>
pub fn get_item_by_index(&self, idx: usize) -> Result<Value, Error>
Looks up an index of the value.
This is a shortcut for get_item
.
let seq = Value::from(vec![0u32, 1, 2]);
let value = seq.get_item_by_index(1).unwrap();
assert_eq!(value.try_into().ok(), Some(1));
sourcepub fn get_item(&self, key: &Value) -> Result<Value, Error>
pub fn get_item(&self, key: &Value) -> Result<Value, Error>
Looks up an item (or attribute) by key.
This is similar to get_attr
but instead of using
a string key this can be any key. For instance this can be used to
index into sequences. Like get_attr
this returns
UNDEFINED
when an invalid key is looked up.
let ctx = minijinja::context! {
foo => "Foo",
};
let value = ctx.get_item(&Value::from("foo")).unwrap();
assert_eq!(value.to_string(), "Foo");
sourcepub fn try_iter(&self) -> Result<ValueIter<'_>, Error>
pub fn try_iter(&self) -> Result<ValueIter<'_>, Error>
Iterates over the value.
Depending on the kind
of the value the iterator
has a different behavior.
ValueKind::Map
: the iterator yields the keys of the map.ValueKind::Seq
: the iterator yields the items in the sequence.ValueKind::None
/ValueKind::Undefined
: the iterator is empty.
let value = Value::from({
let mut m = std::collections::BTreeMap::new();
m.insert("foo", 42);
m.insert("bar", 23);
m
});
for key in value.try_iter()? {
let value = value.get_item(&key)?;
println!("{} = {}", key, value);
}
sourcepub fn downcast_object_ref<T: 'static>(&self) -> Option<&T>
pub fn downcast_object_ref<T: 'static>(&self) -> Option<&T>
Returns some reference to the boxed object if it is of type T
, or None if it isn’t.
This is basically the “reverse” of from_object
,
from_seq_object
and from_struct_object
.
It’s also a shortcut for downcast_ref
on the return value of as_object
.
Example
use std::fmt;
#[derive(Debug)]
struct Thing {
id: usize,
}
impl fmt::Display for Thing {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
impl Object for Thing {}
let x_value = Value::from_object(Thing { id: 42 });
let thing = x_value.downcast_object_ref::<Thing>().unwrap();
assert_eq!(thing.id, 42);
It also works with SeqObject
or StructObject
:
struct Thing {
id: usize,
}
impl SeqObject for Thing {
fn get_item(&self, idx: usize) -> Option<Value> {
(idx < 3).then(|| Value::from(idx))
}
fn item_count(&self) -> usize {
3
}
}
let x_value = Value::from_seq_object(Thing { id: 42 });
let thing = x_value.downcast_object_ref::<Thing>().unwrap();
assert_eq!(thing.id, 42);
sourcepub fn call(
&self,
state: &State<'_, '_>,
args: &[Value]
) -> Result<Value, Error>
pub fn call( &self, state: &State<'_, '_>, args: &[Value] ) -> Result<Value, Error>
Calls the value directly.
If the value holds a function or macro, this invokes it. Note that in
MiniJinja there is a separate namespace for methods on objects and callable
items. To call methods (which should be a rather rare occurrence) you
have to use call_method
.
The args
slice is for the arguments of the function call. To pass
keyword arguments use the Kwargs
type.
Usually the state is already available when it’s useful to call this method,
but when it’s not available you can get a fresh template state straight
from the Template
via new_state
.
let func = Value::from_function(|v: i64, kwargs: Kwargs| {
v * kwargs.get::<i64>("mult").unwrap_or(1)
});
let rv = func.call(
state,
&[
Value::from(42),
Value::from(Kwargs::from_iter([("mult", Value::from(2))])),
],
).unwrap();
assert_eq!(rv, Value::from(84));
With the args!
macro creating an argument slice is
simplified:
let func = Value::from_function(|v: i64, kwargs: Kwargs| {
v * kwargs.get::<i64>("mult").unwrap_or(1)
});
let rv = func.call(state, args!(42, mult => 2)).unwrap();
assert_eq!(rv, Value::from(84));
Trait Implementations§
source§impl<V: Into<Value>> FromIterator<V> for Value
impl<V: Into<Value>> FromIterator<V> for Value
source§fn from_iter<T: IntoIterator<Item = V>>(iter: T) -> Self
fn from_iter<T: IntoIterator<Item = V>>(iter: T) -> Self
source§impl Ord for Value
impl Ord for Value
source§impl PartialEq<Value> for Value
impl PartialEq<Value> for Value
source§impl PartialOrd<Value> for Value
impl PartialOrd<Value> for Value
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
self
and other
) and is used by the <=
operator. Read more