Python Jinjna变量不会在循环外保持值

时间:2017-01-13 13:15:26

标签: python jinja2

我目前正试图通过使用jinja变量解决问题,但不知何故变量不会将值保留在循环之外,即使我在循环开始之前声明它:

{% set disablecounter = 0 %}

{% if disablecounter == 0 %}
    {% for einzelroom in all_einzelzimmer %}
        {% if zimmer.id == einzelroom.zimmer_id %}
            {% set price = einzelroom.preis %}
            <div class="preis-element">
                <p class="preis"> <span class="smallab"> ab </span> {{ price|int }}&euro; </p>
            </div>
            {% set disablecounter = disablecounter + 1 %}
            {{ disablecounter }}
        {% endif %}
    {% endfor %}
{% endif %}

{{ disablecounter }}

变量是disablecounter在循环内1但在它之外仍然是0

谢谢!

修改

围绕with statement并没有奏效:

{% with foo = 42 %}
    {{ foo }}
{% endwith %}

{% with %}
    {% set foo = 42 %}
    {{ foo }}
{% endwith %}

1 个答案:

答案 0 :(得分:0)

@Chris Warth找到了一个很棒的解决方案here on SO

@Peter Hollingsworth的原始答案: https://stackoverflow.com/a/32700975/5291566

{% with disablecounter = [0] %}

{% if disablecounter == [0] %}
    {% for einzelroom in all_einzelzimmer %}
        {% if zimmer.id == einzelroom.zimmer_id %}
            <div class="preis-element">
                <p class="preis"> <span class="smallab"> ab </span> {{ einzelroom.preis|int }}&euro; </p>
            </div>
            {% if disablecounter.append(disablecounter.pop() + 1) %}{% endif %} 
        {% endif %}
    {% endfor %}
{% endif %}