在Jinja中为循环设置变量在两次迭代之间不会持久 [英] Setting variable in Jinja for loop doesn't persist between iterations

查看:64
本文介绍了在Jinja中为循环设置变量在两次迭代之间不会持久的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历对象列表,并计算有多少对象满足要求.我根据发现的其他示例创建了代码,但是它不起作用,循环后的计数始终为0.

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 0 after the loop.

对于每个房子,我想遍历每个房间并计算有多少个房间有一张床.我要输出,然后重置下一个房子的计数.

For each house, I want to loop over each room and count how many rooms have a bed. I want to output that then reset the count for the next house.

{% for house in city %}
{% set count = 0 %}
    <div>{{ house.address }} has {{ count }} beds in it rooms.</div>
    {% for room in house %}
    {% if room.has_bed == True %}{% set count = count + 1 %}{% endif %}
   {% endfor %}
{% endfor %}

推荐答案

对于Jinja 2.9,作用域行为已修复,使在以前版本中可用的代码无效. count的递增值仅在循环范围内. 他们的示例涉及设置变量,但是概念是相同的:

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:

请记住,无法在块内设置变量并使变量显示在块外.这也适用于循环.该规则的唯一例外是if语句未引入作用域.结果,以下模板无法完成您可能期望的操作:

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 %}

Jinja语法无法做到这一点.

It is not possible with Jinja syntax to do this.

您将需要执行一些hacky-ish解决方法,以便在各个迭代之间跟踪count.设置一个列表,追加到列表中,然后计算其长度.

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 %}
    <div>{{ house.address }} has {{ room_count|length }} beds.</div>
{% endfor %}

这篇关于在Jinja中为循环设置变量在两次迭代之间不会持久的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆