13

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?

dreftymac
  • 31,404
  • 26
  • 119
  • 182
applechief
  • 6,615
  • 12
  • 50
  • 70
  • 6
    This sounds like the sort of thing you generally want to do in your python code, not the template. – Wooble Sep 11 '12 at 11:26

3 Answers3

23

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 %}
olly_uk
  • 11,559
  • 3
  • 39
  • 45
  • 1
    This would get the first 5 items of the array, not the ones with author bob.. If i have an array with 10 items and bob wrote the last 5, this will not return anything – applechief Sep 11 '12 at 11:20
  • 1
    i would agree with Wooble, this sort of logic should probably be sorted before you get to the template, maybe make the list a dict of lists with the authors being the keys? – olly_uk Sep 11 '12 at 11:35
  • 1
    what about nested loops? how do access the `loop` variable from a parent loop – bubakazouba Jun 17 '16 at 20:44
7

to skip the first x elements you can

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

with all the expressions you can use for the regular lists

OWADVL
  • 10,704
  • 7
  • 55
  • 67
5

You can also use

{% for item in list[0:6] %}
Raju Sarkar
  • 61
  • 1
  • 3