I want to filter a for loop over a groupby filter based on the loop variable. This is what I'm doing:
{% for group in list_of_dicts | groupby('attribute') -%}
{% if loop.index < 9 %}
...
{% endif %}
{% endfor %}
It works as I expect. In the docs there is this syntax:
{% for user in users if not user.hidden %}
<li>{{ user.username|e }}</li>
{% endfor %}
How to use the above mentioned syntax when looping over a filter? I mean like the following, which raises an UndefinedError:
{% for group in list_of_dicts | groupby('attribute') if loop.index < 9 -%}
...
{% endfor %}
UndefinedError: 'loop' is undefined. the filter section of a loop as well as the else block don't have access to the special 'loop' variable of the current loop. Because there is no parent loop it's undefined. Happened in loop on line 18 in 'page.html'
The filter works like in a normal Python LC (You can just access group).
Using a filter in this case, doesn't make sense anyways. E.g. the grouped list_of_dicts contains let's say, 3000 elements, so you're doing 3000 iterations but you just want 9. You should slice your groups:
{% for group in (list_of_dicts | groupby('attribute'))[:9] -%}
...
{% endfor %}
(Assuming the filter returns a list)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With