How do you sort the list in Jinja2?

I am trying to do this:

{% for movie in movie_list | sort(movie.rating) %} 

But this is not so ... the documentation is foggy ... how do you do it in Jinja2?

+49
python sorting jinja2
Dec 24 '09 at 18:56
source share
3 answers

Starting with version 2.6, the built-in Jinja2 sorting filter allows you to specify an attribute to sort by:

 {% for movie in movie_list|sort(attribute='rating') %} 

See http://jinja.pocoo.org/docs/templates/#sort

+101
Mar 30 '11 at 17:55
source share

We usually sort the list before passing it to Jinja2. There is no way to specify a key in a Jinja sort filter.

However, you can always try {% for movie in movie_list|sort %} . This is the syntax. You cannot provide any key information for sorting.

You can also try creating your own filter. It seems silly when you can sort before passing data to Jinja2.

If movie_list is a list of objects, you can define various comparison methods ( __lt__ , __gt__ , etc.) for the class of these objects.

If movie_list is a list of tuples or lists, the rating should be first. Or you will have to do sorting outside of Jinja2.

If movie_list is a list of dictionaries, you can use dictsort , which accepts a key specification for sorting. Read this: http://jinja.pocoo.org/2/documentation/templates#dictsort for an example.

+11
Dec 24 '09 at 19:06
source share

If you want to sort in ascending order

 {% for movie in movie_list|sort(attribute='rating') %} 

If you want to sort in descending order

 {% for movie in movie_list|sort(attribute='rating', reverse = True) %} 
+5
Aug 20 '16 at 6:41
source share



All Articles