Struct minijinja::value::Value

source ·
pub struct Value(_);
Expand description

Represents a dynamically typed value in the template engine.

Implementations§

source§

impl Value

source

pub const UNDEFINED: Value = _

The undefined value

source

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.

source

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());
source

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 }));
source

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.

source

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.

source

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);
source

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.

source

pub fn is_kwargs(&self) -> bool

Returns true if the map represents keyword arguments.

source

pub fn is_true(&self) -> bool

Is this value true?

source

pub fn is_safe(&self) -> bool

Returns true if this value is safe.

source

pub fn is_undefined(&self) -> bool

Returns true if this value is undefined.

source

pub fn is_none(&self) -> bool

Returns true if this value is none.

source

pub fn as_str(&self) -> Option<&str>

If the value is a string, return it.

source

pub fn as_bytes(&self) -> Option<&[u8]>

Returns the bytes of this value if they exist.

source

pub fn as_object(&self) -> Option<&dyn Object>

If the value is an object, it’s returned as Object.

source

pub fn as_seq(&self) -> Option<&dyn SeqObject>

If the value is a sequence it’s returned as SeqObject.

source

pub fn as_struct(&self) -> Option<&dyn StructObject>

If the value is a struct, return it as StructObject.

source

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));
source

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");
source

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));
source

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");
source

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.

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);
}
source

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<'a> ArgType<'a> for &Value

§

type Output = &'a Value

The output type of this argument.
source§

impl<'a> ArgType<'a> for Value

§

type Output = Value

The output type of this argument.
source§

impl Clone for Value

source§

fn clone(&self) -> Value

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Value

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl Default for Value

source§

fn default() -> Value

Returns the “default value” for a type. Read more
source§

impl<'de> Deserialize<'de> for Value

source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl Display for Value

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<'a> From<&'a [u8]> for Value

source§

fn from(val: &'a [u8]) -> Self

Converts to this type from the input type.
source§

impl<'a> From<&'a str> for Value

source§

fn from(val: &'a str) -> Self

Converts to this type from the input type.
source§

impl From<()> for Value

source§

fn from(_: ()) -> Self

Converts to this type from the input type.
source§

impl From<Arc<String>> for Value

source§

fn from(value: Arc<String>) -> Self

Converts to this type from the input type.
source§

impl<T: Object> From<Arc<T>> for Value

source§

fn from(object: Arc<T>) -> Self

Converts to this type from the input type.
source§

impl From<Arc<Vec<Value, Global>>> for Value

source§

fn from(val: Arc<Vec<Value>>) -> Self

Converts to this type from the input type.
source§

impl From<Arc<Vec<u8, Global>>> for Value

source§

fn from(val: Arc<Vec<u8>>) -> Self

Converts to this type from the input type.
source§

impl From<Arc<dyn Object + 'static>> for Value

source§

fn from(val: Arc<dyn Object>) -> Self

Converts to this type from the input type.
source§

impl<K: Into<Key<'static>>, V: Into<Value>> From<BTreeMap<K, V, Global>> for Value

source§

fn from(val: BTreeMap<K, V>) -> Self

Converts to this type from the input type.
source§

impl<'a> From<Cow<'a, str>> for Value

source§

fn from(val: Cow<'a, str>) -> Self

Converts to this type from the input type.
source§

impl<K: Into<Key<'static>>, V: Into<Value>> From<HashMap<K, V, RandomState>> for Value

source§

fn from(val: HashMap<K, V>) -> Self

Converts to this type from the input type.
source§

impl From<String> for Value

source§

fn from(val: String) -> Self

Converts to this type from the input type.
source§

impl From<Value> for String

source§

fn from(val: Value) -> Self

Converts to this type from the input type.
source§

impl<T: Into<Value>> From<Vec<T, Global>> for Value

source§

fn from(val: Vec<T>) -> Self

Converts to this type from the input type.
source§

impl From<bool> for Value

source§

fn from(val: bool) -> Self

Converts to this type from the input type.
source§

impl From<char> for Value

source§

fn from(val: char) -> Self

Converts to this type from the input type.
source§

impl From<f32> for Value

source§

fn from(val: f32) -> Self

Converts to this type from the input type.
source§

impl From<f64> for Value

source§

fn from(val: f64) -> Self

Converts to this type from the input type.
source§

impl From<i128> for Value

source§

fn from(val: i128) -> Self

Converts to this type from the input type.
source§

impl From<i16> for Value

source§

fn from(val: i16) -> Self

Converts to this type from the input type.
source§

impl From<i32> for Value

source§

fn from(val: i32) -> Self

Converts to this type from the input type.
source§

impl From<i64> for Value

source§

fn from(val: i64) -> Self

Converts to this type from the input type.
source§

impl From<i8> for Value

source§

fn from(val: i8) -> Self

Converts to this type from the input type.
source§

impl From<u128> for Value

source§

fn from(val: u128) -> Self

Converts to this type from the input type.
source§

impl From<u16> for Value

source§

fn from(val: u16) -> Self

Converts to this type from the input type.
source§

impl From<u32> for Value

source§

fn from(val: u32) -> Self

Converts to this type from the input type.
source§

impl From<u64> for Value

source§

fn from(val: u64) -> Self

Converts to this type from the input type.
source§

impl From<u8> for Value

source§

fn from(val: u8) -> Self

Converts to this type from the input type.
source§

impl From<usize> for Value

source§

fn from(val: usize) -> Self

Converts to this type from the input type.
source§

impl<K: Into<Key<'static>>, V: Into<Value>> FromIterator<(K, V)> for Value

source§

fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self

Creates a value from an iterator. Read more
source§

impl<V: Into<Value>> FromIterator<V> for Value

source§

fn from_iter<T: IntoIterator<Item = V>>(iter: T) -> Self

Creates a value from an iterator. Read more
source§

impl PartialEq<Value> for Value

source§

fn eq(&self, other: &Self) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd<Value> for Value

source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl Serialize for Value

source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>where S: Serializer,

Serialize this value into the given Serde serializer. Read more
source§

impl TryFrom<Value> for bool

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(value: Value) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Value> for char

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(value: Value) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Value> for f32

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(value: Value) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Value> for f64

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(value: Value) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Value> for i128

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(value: Value) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Value> for i16

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(value: Value) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Value> for i32

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(value: Value) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Value> for i64

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(value: Value) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Value> for i8

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(value: Value) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Value> for u128

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(value: Value) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Value> for u16

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(value: Value) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Value> for u32

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(value: Value) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Value> for u64

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(value: Value) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Value> for u8

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(value: Value) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<Value> for usize

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(value: Value) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl Eq for Value

Auto Trait Implementations§

§

impl !RefUnwindSafe for Value

§

impl Send for Value

§

impl Sync for Value

§

impl Unpin for Value

§

impl !UnwindSafe for Value

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

const: unstable · source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for Twhere T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
const: unstable · source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>,