tera icon indicating copy to clipboard operation
tera copied to clipboard

Distinguishing between `false` and `null`.

Open pinkisemils opened this issue 2 years ago • 1 comments

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.

pinkisemils avatar Jun 11 '22 02:06 pinkisemils

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::field is Some(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 %}

joshleeb avatar Jun 11 '22 02:06 joshleeb