Jinja2 first x items in for ... if loop

I have the following loop in my jinja2 template

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

I am trying to get the first 5 elements that have bob as the author.

I tried to do

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

but he returned an undefined error.

How to make it work?

+5
source share
2 answers

EDIT:

can you just nest the expressions ?, i.e.

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

to skip the first x elements you can

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

with all the expressions you can use for regular lists

+3
source

All Articles