Reputation: 701
I want to count the number of items in a list that have a specific value and print this count before and after I loop over the items. I tried the following:
{% set counter = [] %}
Counter : {{ counter|length }}
{% for i in array %}
{% if i['maybe_true'] %}
{% if counter.append('1') %}{% endif %}
{% endif %}
{% endfor %}
Counter : {{ counter|length }}
Rendering this produces different values before and after, as expected.
Counter : 0
Counter : 100
Is it possible to get 100 before the loop too?
Upvotes: 1
Views: 910
Reputation: 127180
To your direct question: no, you can't render a variable before you calculate it.
Use a selectattr
filter. It returns a generator, so use the list
filter before using length
.
{{ array|selectattr('maybe_true')|list|length }}
If your actual code is more complex than this, consider moving the logic to Python then sending the processed data to the template.
true_items = [i for i in array if i.maybe_true]
return render_template('index.html', array=array, true_items=true_items)
{{ true_items|length }}
{% for i in array %}
...
{% endfor %}
{{ true_items|length }}
Upvotes: 4