Keats / tera

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

[FEATURE REQUEST] Support comparison operators for strings #893

Closed MaSteve closed 8 months ago

MaSteve commented 8 months ago

Hi,

I noticed that the current version of Tera only supports the comparison operators for numbers. I find that quite limiting for example when comparing dates in ISO format or similar use cases where the alphabetical order is used. A workaround for this resorts in using an array and sorting it, but it is a bit convoluted.

I couldn’t find a similar issue nor any mention of this in the wishlist for v2, so I decided to open this issue to discuss this feature.

Thanks!

Keats commented 8 months ago

String comparison is a feature that will definitely NOT be added. The only valid use-case for it as you is ISO formatted dates so way too narrow

schungx commented 7 months ago

well I just happen to want to compare dates... what should I use?

schungx commented 4 months ago

For those who're interested, it is simple to register a strcmp function:

tera.register_function("strcmp", |args: &HashMap<String, Value>| {
    let a = args.get("a").and_then(Value::as_str).unwrap_or("");
    let b = args.get("b").and_then(Value::as_str).unwrap_or("");

    match a.cmp(b) {
        std::cmp::Ordering::Less => Ok((-1).into()),
        std::cmp::Ordering::Equal => Ok(0.into()),
        std::cmp::Ordering::Greater => Ok(1.into()),
    }
});

Usage:

{% if strcmp(a=first_string, b=second_string) >= 0 %} ... {% endif %}