jinja2第一个x项目为...如果循环

app*_*ief 5 python jinja2 flask

我的jinja2模板中有以下循环

{% for item in list if item.author == 'bob' %}
Run Code Online (Sandbox Code Playgroud)

我试图获得作为作者有bob的前5个项目.

我试过了

{% for item in list if item.author == 'bob' and loop.index <= 5 %}
Run Code Online (Sandbox Code Playgroud)

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

如何使它工作?

oll*_*_uk 12

编辑:

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

{% for item in list if item.author == 'bob' %}
    {% if loop.index <= 5 %}
       do something
    {% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)


OWA*_*DVL 6

跳过前 x 个元素,你可以

{% for category in categories[x:] %}
Run Code Online (Sandbox Code Playgroud)

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


小智 5

您还可以使用

{% for item in list[0:6] %}
Run Code Online (Sandbox Code Playgroud)