13

我的 jinja2 模板中有以下循环

{% for item in list if item.author == 'bob' %}

我正在尝试获取以 bob 作为作者的前 5 个项目。

我试着做

{% for item in list if item.author == 'bob' and loop.index <= 5 %}

但它返回了一个未定义的错误。

如何让它发挥作用?

4

3 回答 3

16

编辑:

你可以简单地嵌套表达式?,即

{% for item in list if item.author == 'bob' %}
    {% if loop.index <= 5 %}
       do something
    {% endif %}
{% endfor %}
于 2012-09-11T11:19:39.587 回答
7

跳过前 x 个元素,你可以

{% for category in categories[x:] %}

使用所有可用于常规列表的表达式

于 2015-05-05T12:30:16.793 回答
4

你也可以使用

{% for item in list[0:6] %}
于 2019-01-05T23:33:21.377 回答