askama icon indicating copy to clipboard operation
askama copied to clipboard

Unable to compare integer from a loop (reference)

Open Ummon opened this issue 2 years ago • 1 comments

This very simple case raises an error at compilation:

error[E0308]: mismatched types
 --> src\main.rs:3:10
  |
3 | #[derive(Template)]
  |          ^^^^^^^^ expected `i32`, found `&i32`
  |
  = note: this error originates in the derive macro `Template` (in Nightly builds, run with -Z macro-backtrace for more info)
use askama::Template;

#[derive(Template)]
#[template(source  = "
{% for (id, title) in titles %}
    {% if current_id.is_some() && current_id.unwrap() == id %}
        <b>{{ title }}</b>
    {% else %}
        {{ title }}
    {% endif %}
{% endfor %}
", ext = "html")]
struct MyTemplate {
    titles: Vec<(i32, String)>,
    current_id: Option<i32>,
}

fn main() {
    let titles = MyTemplate { titles: vec![(1, "AAA".to_string()), (2, "BBB".to_string())], current_id: Some(1) };
    println!("{}", titles.render().unwrap());
}

The only solution I found is a bit ugly (it seems Askama doesn't support guarded cases):

{% for (id, title) in titles %}
    {% match current_id %}
        {% when Some with (current_id_value) %}
            {% if current_id_value == id %}
                <b>{{ title }}</b>
            {% else %}
                {{ title }}
            {% endif %}
        {% when None %}
            {{ title }}
        {% endmatch %}
{% endfor %}

I also tried with 'eq(..)' without success.

Ummon avatar Nov 28 '22 22:11 Ummon