jinja2的前x个项目。。。if循环

2024-05-14 07:37:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我的jinja2模板中有以下循环

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

我试着得到前5个项目谁有鲍勃作为一个作家。

我试过了

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

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

如何让它工作?


Tags: and项目inloop模板jinja2forindex
3条回答

要跳过前x个元素,可以

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

使用所有可用于正则列表的表达式

你也可以使用

{% for item in list[0:6] %}

编辑:

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

{% for item in list if item.author == 'bob' %}
    {% if loop.index <= 5 %}
       do something
    {% endif %}
{% endfor %}

相关问题 更多 >

    热门问题