Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you sort a list in Jinja2?

I am trying to do this:

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

But that's not right...the documentation is vague...how do you do this in Jinja2?

like image 412
Nick Perkins Avatar asked Dec 24 '09 18:12

Nick Perkins


People also ask

How do you write a for loop in Jinja2?

Jinja2 being a templating language has no need for wide choice of loop types so we only get for loop. For loops start with {% for my_item in my_collection %} and end with {% endfor %} . This is very similar to how you'd loop over an iterable in Python.


2 Answers

As of version 2.6, Jinja2's built-in sort 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

like image 149
Steve S Avatar answered Oct 07 '22 21:10

Steve S


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) %} 
like image 35
SumanKalyan Avatar answered Oct 07 '22 22:10

SumanKalyan