Setting variable in Jinja for loop doesn't persist between iterations

后端 未结 3 1043
既然无缘
既然无缘 2021-01-19 16:27

I want to loop over a list of objects and count how many objects meet a requirement. I based my code off other examples I\'d found, but it doesn\'t work, the count is always

3条回答
  •  没有蜡笔的小新
    2021-01-19 17:16

    For Jinja <= 2.8, the code you've shown does work. However, this was due to incorrect behavior in Jinja's scope rules, which was fixed in 2.9.

    {% for house in city %}
        {% set count = 0 %}
        {% for room in house %}
            {% if room.has_bed %}
                {% set count = count + 1 %}
            {% endif %}
        {% endfor %}
        
    {{ house.address }} has {{ count }} beds.
    {% endfor %}

提交回复
热议问题