jinja2 first x items in for ... if loop


Question

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 items who have bob as an author.

I tried doing

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

but it returned an undefined error.

How to make it work?

1
5
9/11/2012 11:16:42 AM

Accepted Answer

EDIT:

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

{% for item in list if item.author == 'bob' %}
    {% if loop.index <= 5 %}
       do something
    {% endif %}
{% endfor %}
12
9/11/2012 11:28:08 AM

to skip the first x elements you can

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

with all the expressions you can use for the regular lists


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon