Keats / tera

A template engine for Rust based on Jinja2/Django
http://keats.github.io/tera/
MIT License
3.54k stars 283 forks source link

Add builtin `is none` or `is null` test #782

Open hwittenborn opened 1 year ago

hwittenborn commented 1 year ago

I'd consider checking if a value is null to be a pretty common task, and I think it'd be a pretty good candidate for a builtin function.

Currently I have the following in my application:

/// Check if a value is [`Value::Null`].
pub fn none(value: Option<&Value>, _args: &[Value]) -> Result<bool> {
    Ok(value.unwrap().is_null())
}

And yeah it's just three lines of code, but having this available everywhere just feels like it would be a good idea, especially for people who'd be coming from Jinja where this would be built in.

Keats commented 1 year ago

I think this is ok to add, i'm just a bit worried about confusion between null and not defined but it's probably ok.

hwittenborn commented 1 year ago

A description could just be added that not defined means the variable isn't present, and null just checks if the variable is set to Option::None, right? I don't know what the current description for defined is, but the stuff I said seemed to make enough sense - what do you think?

Keats commented 1 year ago

Yep that's exactly that. I had a few people confused on defined vs null already, expecting null_var is defined to be true which is a reasonable take I think. Maybe defined is not the right word

hwittenborn commented 1 year ago

expecting null_var is defined to be true

Yeah I agree, as long as the variable is present I think is defined should return true, and then yeah is null specifically for Option::None values (or I guess Value::Null in the library since it uses that serde_json stuff).

Maybe defined is not the right word

I think it is, I must say I was checking is defined to see how it would react to a null value, but my intuition was still originally telling me that defined would check if the variable itself existed. I think with an is none check that ambiguity could be cleared up, and a note or something clarifying when to use each could be added too.