tera
tera copied to clipboard
Distinguishing between `false` and `null`.
Given a struct like Foo
#[derive(serde::Serialize)]
struct Foo {
field: Option<bool>,
}
How would one distinguish between a None and a Some(false) value of Foo::field?
If a tera context is created from the struct above {{ field is defined }} will always evaluate to true since it is defined.
I would suggest writing and registering a custom Test function where the implementation depends on how you want to distinguish between None and Some(false). I'll assume that you want something that evaluates to
- true if
Foo::fieldisSome(true) - false otherwise (i.e: not defined,
None,Some(false))
which could look something like
fn is_truthy(value: Option<&Value>, _args: &[Value]) -> tera::Result<bool> {
if let Some(Value::Bool(true)) = value {
return true;
}
false
}
And then, once registered with your Tera instance (assuming you've registered it with the identifier truthy) you can use it in the template with
{% if x is truthy %}
It's truthy!
{% endif %}