How do you sort a list in Jinja2?
Asked Answered
H

2

125

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?

Hoop answered 24/12, 2009 at 18:56 Comment(0)
A
224

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

Alterant answered 30/3, 2011 at 17:55 Comment(4)
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)Hoop
@Nick: I did a quick test, and it seemed to work with both objects and dicts.Alterant
Nice, this also works for a tuple index: list_of_tuples|sort(attribute='0')Billionaire
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.Carabineer
E
48

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) %}
Evaleen answered 20/8, 2016 at 6:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.