'if with jinja2 always false [duplicate]
I have the following code, I get persons from sqlalchemy query and Flask, I want to print the shift only when is different, but the condition is always false. I don't know what happen:
{% set actual_shift = 0 %}
{% for person in persons %}
{% if actual_shift == person.shift|safe %}
<p></p>
{% else %}
{% set actual_shift = person.shift |safe %}
{% set actual_shift = actual_shift |int %}
<p>{{ actual_shift }}</p>
{% endif %}
<label class="form-check-label" for="{{ person.username }}"><input type="checkbox" value="{{person.person_id}}" class="form-check-input" id="{{ person.username }}" name="persons" checked>{{person.fname}} {{person.lname}}</label>
{% endfor %}
Solution 1:[1]
If you want to assign a new value to your variable inside a loop of jinja2, you should define a namespace. You can find the documentation for this here.
{% set actual = namespace(shift=0) %}
{% for person in persons %}
{% if actual.shift == person.shift %}
<p></p>
{% else %}
{% set actual.shift = person.shift %}
<p>{{ actual.shift }}</p>
{% endif %}
{% endfor %}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Detlef |
