How do you sort a list in Jinja2?

PythonSortingJinja2

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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) %}

Solution 3 - Python

Usually we sort the list before giving it to Jinja2. 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.

You can also try and write a custom filter for this. Seems silly when you can sort before giving the data to Jinja2.

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

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick PerkinsView Question on Stackoverflow
Solution 1 - PythonSteve SView Answer on Stackoverflow
Solution 2 - PythonSumanKalyanView Answer on Stackoverflow
Solution 3 - PythonS.LottView Answer on Stackoverflow