Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Problems comparing integers #894

Open
pliniocampinas opened this issue Oct 29, 2023 · 1 comment
Open

Problems comparing integers #894

pliniocampinas opened this issue Oct 29, 2023 · 1 comment

Comments

@pliniocampinas
Copy link

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?

@vallentin
Copy link
Collaborator

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants