117

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?

Sridhar Ratnakumar
  • 81,433
  • 63
  • 146
  • 187
Nick Perkins
  • 8,034
  • 7
  • 40
  • 40

2 Answers2

213

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

Steve S
  • 5,256
  • 1
  • 29
  • 26
  • Thanks, that's exactly what I wanted. By the way, does it work with both types of attributes...you know __getattr__ and __getitem__ ? (because I can't remember whether "movies" were objects or dictionaries) – Nick Perkins Mar 31 '11 at 23:28
  • @Nick: I did a quick test, and it seemed to work with both objects and dicts. – Steve S Apr 01 '11 at 15:39
  • 3
    Nice, this also works for a tuple index: `list_of_tuples|sort(attribute='0')` – Navin Jul 11 '18 at 19:11
  • 1
    It could be handy to display values in reverse orders (it could be interesting for ratings for example), in this case just use the option `reverse=True`. – Romain Oct 21 '18 at 19:20
44

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) %}
SumanKalyan
  • 1,681
  • 14
  • 24