3

変数に基づいてフィルターをfor loopフィルター処理したいと思います。これは私がしていることです:groupbyloop

{% for group in list_of_dicts | groupby('attribute') -%}
    {% if loop.index < 9 %}
    ...
    {% endif %}
{% endfor %}

期待どおりに動作します。ドキュメントには、次の構文があります。

{% for user in users if not user.hidden %}
    <li>{{ user.username|e }}</li>
{% endfor %}

フィルタをループするときに上記の構文を使用するにはどうすればよいですか?私は次のように意味します、それは:を上げ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'
4

1 に答える 1

3

フィルタは、通常の Python LC のように機能します (単にアクセスできますgroup)。

この場合にフィルタを使用しても意味がありません。たとえば、グループ化されたlist_of_dicts要素に 3000 個の要素が含まれているため、3000 回の反復を実行していますが、必要なのは 9 回だけです。グループをスライスする必要があります。

{% for group in (list_of_dicts | groupby('attribute'))[:9] -%}
    ...
{% endfor %}

(フィルターがリストを返すと仮定します)

于 2012-04-20T13:20:44.677 に答える