Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop variable in a filtered loop

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'
like image 265
Clodoaldo Neto Avatar asked Dec 12 '25 15:12

Clodoaldo Neto


1 Answers

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)

like image 188
dav1d Avatar answered Dec 15 '25 09:12

dav1d