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

后端 未结 3 1017
既然无缘
既然无缘 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.9, the scope behavior was fixed, invalidating code that worked in previous versions. The incremented value of count only lives within the scope of the loop. Their example involves setting variables, but the concept is the same:

    Please keep in mind that it is not possible to set variables inside a block and have them show up outside of it. This also applies to loops. The only exception to that rule are if statements which do not introduce a scope. As a result the following template is not going to do what you might expect:

    {% set iterated = false %}
    {% for item in seq %}
        {{ item }}
        {% set iterated = true %}
    {% endfor %}
    {% if not iterated %} did not iterate {% endif %}
    

    It is not possible with Jinja syntax to do this.

    You will need to do a hacky-ish workaround in order to track count across iterations. Set a list, append to it, then count its length.

    {% for house in city %}
        {% set room_count = [] %}
        {% for room in house %}
            {% if room.has_bed %}
                {% if room_count.append(1) %}{% endif %}
            {% endif %}
        {% endfor %}
        
    {{ house.address }} has {{ room_count|length }} beds.
    {% endfor %}

提交回复
热议问题