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.
There's no way to specify a key in Jinja's sort filter. However, you can always try {% for movie in movie_list|sort %} . That's the syntax. You don't get to provide any sort of key information for the sorting.
Jinja2 allows us to manually control generation of whitespaces. You do it by using a minus sing - to strip whitespaces from blocks, comments or variable expressions. You need to add it to the start or end of given expression to remove whitespaces before or after the block, respectively.
It is a text-based template language and thus can be used to generate any markup as well as source code. The Jinja template engine allows customization of tags, filters, tests, and globals. Also, unlike the Django template engine, Jinja allows the template designer to call functions with arguments on objects.
Synopsis. A Jinja template is simply a text file. Jinja can generate any text-based format (HTML, XML, CSV, LaTeX, etc.). A Jinja template doesn't need to have a specific extension: . html , .
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 %}
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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With