Reputation: 8338
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
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
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