2012-04-20 22 views
1

loop変数に基づいてgroupbyフィルタを介してfor loopをフィルタリングしたいとします。これは私がやっていることです:フィルタリングされたループ内のループ変数

{% 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 %} 

フィルタをループするときに上記の構文を使用するにはどうすればよいですか?

{% 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' 

答えて

3

フィルタは、通常のPython LC(あなたがgroupにだけアクセスすることができます)でのように動作します:私はUndefinedErrorを提起され、次のような意味します。

この場合、フィルタを使用しても意味がありません。例えば。グループ化されたlist_of_dictsは、あなたが3000回の繰り返しをやっているので、3000個の要素、のは言わせ含まれていますが、単に9.あなたのグループをスライスする必要がありたい:

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

(フィルタがリストを返すと仮定します)
関連する問題