pub struct Value(_);
Expand description
Represents a dynamically typed value in the template engine.
Implementations§
source§impl 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]);
Panics
This method panics if types are passed which are not supported by the underlying rendering system. Today this is the case for value types that have unrepresentable keys. The desire is that eventually this call will no longer panic under any circumstances.
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
Creates a value from an owned SeqObject
.
This is a simplified API for creating dynamic sequences
without having to implement the entire Object
protocol.
Note: objects created this way cannot be downcasted via
downcast_object_ref
.
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.
Note: objects created this way cannot be downcasted via
downcast_object_ref
.
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: 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
. 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);
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 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