0
假设我有一个对象或字符串数组,我想用具有特定值的属性来计算数组中对象的数量。使用Jinja2计算具有特定值的列表中的元素
神社已经提供了用于遍历具有特定值的元素:
{% set list = [dict(a=1),dict(a=2),dict(a=1)] %}
{{ list }}<br/>
{% for e in list if e.a == 1 %}
...
{% endfor %}
我只是想知道有多少次在for循环会进行评估。
我已经能够拿出是使用loop.last
变量来评估对上述循环
{% set list = [dict(a=1),dict(a=2),dict(a=1)] %}
{{ list }}<br/>
{% for e in list if e.a == 1 %}
{% if loop.last %}
list contains {{ loop.index }} elements with a=1
{% endif %}
{% endfor %}
这最后一次迭代我的表达是最好的,但是,不会,如果工作匹配项目的数量为零。我可以明显地把有条件的内循环来解决这个问题
{% set list = [dict(a=1),dict(a=2),dict(a=1)] %}
{{ list }}<br/>
{% for e in list %}
{% if e.a == 1 %}
{% set count = count|d(0) + 1 %}
{% endif %}
{% if loop.last %}
list contains {{ count }} elements with a=1
{% endif %}
{% endfor %}
现在会被罚款,只要列表不为空(在我的名单是不会为空)。
另一个明显的答案是将函数添加到可用于执行此计算的全局上下文,但我很惊讶这样的功能尚不存在。
我的目标是在表中存在特定值时更改某些表格标题的样式。