14

Jinja allows me to do

{% for item in all_items %}
    {{ item }}
{% endfor %}

but I'd like to be able to only take the first n items; in Python that would be

for item in all_items[:n]:

Is there any elegant way to do this in Jinja, except

{% for item in all_items %}
    {% if loop.index <= n %}
        {{ item }}
    {% endif %}
{% endfor %}
miku
  • 181,842
  • 47
  • 306
  • 310
Manuel Ebert
  • 8,429
  • 4
  • 40
  • 61

1 Answers1

27

You can use normal python slice syntax.

>>> import jinja2
>>> t = jinja2.Template("{% for i in items[:3] %}{{ i }}\n{% endfor %}")
>>> items = range(10)
>>> print(t.render(items=items))
0
1
2
jcollado
  • 39,419
  • 8
  • 102
  • 133
miku
  • 181,842
  • 47
  • 306
  • 310