skyler
skyler

Reputation: 8338

How to slice a sorted list in Jinja?

I have a list of dictionaries. I want to first sort that list, then only iterate over a subset of those items.

This is what I tried:

{% for response in responses|sort(true, attribute='response_date')[:5] %}
    <p>response</p>
{% endfor %}

But Jinja doesn't like this syntax, and raises the error TemplateSyntaxError: expected token 'end of statement block', got '['

If I don't use the sort() filter, the slice works. But I want to use both together.

Upvotes: 17

Views: 20211

Answers (2)

Wondercricket
Wondercricket

Reputation: 7872

You can achieve this by wrapping your sort in a parentheses:

{% for response in (responses|sort(true, attribute='response_date'))[:5] %}
   <p>response</p>
{% endfor %}

Upvotes: 16

vaultah
vaultah

Reputation: 46533

Can't you simply wrap responses|sort(true, attribute='response_date') with parentheses?

{% for response in (responses|sort(true, attribute='response_date'))[:5] %}
    <p>response</p>
{% endif %}

Upvotes: 7

Related Questions