循环变量在过滤循环中

时间:2012-04-20 12:46:00

标签: python templates jinja2

我想根据for loop变量在groupby过滤器上过滤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 %}

循环过滤器时如何使用上述语法?我的意思是如下,它引发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'

1 个答案:

答案 0 :(得分:3)

过滤器的工作方式类似于普通的Python LC(您只能访问group)。

在这种情况下使用过滤器,无论如何都没有意义。例如。分组list_of_dicts包含让我们说3000个元素,所以你要做3000次迭代,但你只想要9.你应该对你的组进行切片:

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

(假设过滤器返回一个列表)