Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to slice a sorted list in Jinja?

Tags:

python

jinja2

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.

like image 752
skyler Avatar asked Jul 08 '15 19:07

skyler


People also ask

How do I sort a list in Jinja?

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.

How do you get rid of whitespace in Jinja?

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.

How does Jinja templating work?

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.

What is Jinja format?

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 , .


2 Answers

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 %}
like image 60
Wondercricket Avatar answered Oct 09 '22 11:10

Wondercricket


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 %}
like image 45
vaultah Avatar answered Oct 09 '22 12:10

vaultah