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 %}
現在會被罰款,只要列表不爲空(在我的名單是不會爲空)。
另一個明顯的答案是將函數添加到可用於執行此計算的全局上下文,但我很驚訝這樣的功能尚不存在。
我的目標是在表中存在特定值時更改某些表格標題的樣式。