pub struct Value(_);
Expand description
Represents a dynamically typed value in the template engine.
Implementations
sourceimpl Value
impl Value
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]);
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_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_slice(&self) -> Result<&[Value], Error>
pub fn as_slice(&self) -> Result<&[Value], Error>
If the value is a sequence it’s returned as slice.
let seq = Value::from(vec![1u32, 2, 3, 4]);
let slice = seq.as_slice().unwrap();
assert_eq!(slice.len(), 4);
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<Iter<'_>, Error>
pub fn try_iter(&self) -> Result<Iter<'_>, 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: Object>(&self) -> Option<&T>
pub fn downcast_object_ref<T: Object>(&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
.
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);
Trait Implementations
sourceimpl<K: Into<Key<'static>>, V: Into<Value>> FromIterator<(K, V)> for Value
impl<K: Into<Key<'static>>, V: Into<Value>> FromIterator<(K, V)> for Value
sourcefn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self
sourceimpl<V: Into<Value>> FromIterator<V> for Value
impl<V: Into<Value>> FromIterator<V> for Value
sourcefn from_iter<T: IntoIterator<Item = V>>(iter: T) -> Self
fn from_iter<T: IntoIterator<Item = V>>(iter: T) -> Self
sourceimpl PartialOrd<Value> for Value
impl PartialOrd<Value> for Value
sourcefn partial_cmp(&self, other: &Self) -> Option<Ordering>
fn partial_cmp(&self, other: &Self) -> Option<Ordering>
1.0.0 · sourcefn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
self
and other
) and is used by the <=
operator. Read more