djc / askama

Type-safe, compiled Jinja-like templates for Rust

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Problems comparing integers

pliniocampinas opened this issue · comments

Hi, I just started to test askama but Im having all sorts of problems with integers within a template file. For example, the following code:

{% for solution in solutions %}
 <div class="table">
   {% for row in 0..8 %}
   <div class="row">
     {% for col in 0..8 %}
     <div class="col">
       {% let has_queen = (solution[row] + 0) == col %}
       {% if has_queen -%}
         <img class="queen-icon" src="/_assets/chess-queen.svg" alt="Q">
       {%- endif -%}
     </div>
     {% endfor %}
   </div>
   {% endfor %}
 </div>
 {% endfor %}

{% let has_queen = (solution[row] + 0) == col %} Results on an error: no implementation for &isize == {integer}

But if I just add zero:

{% let has_queen = (solution[row] + 0) == col %}

It compiles.

I also had problems comparing integers. Resulting on errors as no implementation for isize == usize``.

I had no success trying any kind of convertion. Am I missing something here?

The reason adding 0 works, but comparing doesn't is because Rust implements Add for references as well, out of convenience. The same is however not true for PartialEq. So when you add 0, it's able to perform &T + T -> T. Which then allows T == T to compile. Whereas &T == T does not compile.

So why does this happen? In Askama we're trying to hide away references and borrowing. So some expressions automatically borrows values. For common cases, this is usually fine. But the more logic is being added to a template, then you can run into issues like yours.

The easiest way to fix your issue, is instead of using ==, then replace it with .eq(), i.e. {% let has_queen = solution[row].eq(col) %} works fine (assuming T: PartialEq<Rhs> was already valid).

When it comes to putting a lot of logic into a template. Then custom filters or otherwise helper functions or helper traits, can help a lot to move logic out of templates. In your example that isn't by any means a lot of logic though, you just ran into one of the edge cases.