Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping over subset in Jinja

Tags:

python

jinja2

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 %}
like image 233
Manuel Ebert Avatar asked Mar 07 '12 22:03

Manuel Ebert


1 Answers

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
like image 124
miku Avatar answered Oct 21 '22 13:10

miku