How to Sort A List In Jinja2?

5 minutes read

In Jinja2, you can sort a list using the sort filter provided by the template engine. The sort filter arranges the elements of a list in ascending order.


Here's an example of how you can use the sort filter in Jinja2:

1
2
3
4
{% set my_list = [4, 2, 1, 3] %}
{% set sorted_list = my_list | sort %}

Sorted List: {{ sorted_list }}


In the above example, we have a list called my_list, which contains the numbers [4, 2, 1, 3]. The sort filter is applied to my_list using the | syntax, and the sorted list is stored in the variable sorted_list. Finally, the sorted list is printed using the {{ }} syntax.


The output will be:

1
Sorted List: [1, 2, 3, 4]


In addition to sorting a list of numbers, you can also sort a list of strings or objects based on a specific attribute. For example:

1
2
3
4
{% set my_list = ['banana', 'apple', 'grape'] %}
{% set sorted_list = my_list | sort %}

Sorted List: {{ sorted_list }}


Output:

1
Sorted List: ['apple', 'banana', 'grape']


Sorting a list in Jinja2 is straightforward using the sort filter.


How to sort a list ignoring leading/trailing whitespace in Jinja2?

In Jinja2, you can use the sort filter along with a custom filter to ignore leading and trailing whitespace when sorting a list.


First, create a custom filter to remove leading and trailing whitespace from each item in the list. You can do this by using the strip filter provided by Jinja2.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from jinja2 import Template

def strip_whitespace(item):
    return item.strip()

template = Template('''
{% for item in my_list|sort_by_ignoring_whitespace %}
    {{ item }}
{% endfor %}
''')

template.environment.filters['strip_whitespace'] = strip_whitespace


Next, use the sort filter along with the custom filter in your template. Call the custom filter strip_whitespace on each item in the list before sorting it.

1
2
3
4
5
6
7
template = Template('''
{% for item in my_list|sort_by_ignoring_whitespace %}
    {{ item }}
{% endfor %}
''')

template.environment.filters['strip_whitespace'] = strip_whitespace


Now, in your template, you can use the new sort_by_ignoring_whitespace filter to sort the list while ignoring leading and trailing whitespace.

1
2
3
4
5
6
7
template = Template('''
{% for item in my_list|sort_by_ignoring_whitespace %}
    {{ item }}
{% endfor %}
''')

template.environment.filters['strip_whitespace'] = strip_whitespace


Make sure to pass your list to the template using the render method.

1
2
3
4
my_list = ['   Apple   ', '  Orange  ', '  Banana  ']

output = template.render(my_list=my_list)
print(output)


This will output:

1
2
3
Apple
Banana
Orange



How to sort a list by multiple attributes in Jinja2?

In Jinja2, you can sort a list by multiple attributes using the sort filter and the attribute function. Here is an example of sorting a list of dictionaries by two attributes:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
{% set my_list = [
    {'name': 'John', 'age': 25, 'score': 80},
    {'name': 'Jane', 'age': 30, 'score': 90},
    {'name': 'Bob', 'age': 25, 'score': 95},
    {'name': 'Alice', 'age': 35, 'score': 85}
] %}

{% set sorted_list = my_list | sort(attribute('age')) | sort(attribute('score'), reverse=True) %}

{% for item in sorted_list %}
    {{ item.name }} - Age: {{ item.age }} - Score: {{ item.score }}
{% endfor %}


In this example, we first sort the list by the age attribute using the sort filter. The resulting list will have items sorted by age. Then, we use the sort filter again to sort the already sorted list by the score attribute in reverse order. The resulting sorted_list will contain items sorted first by age and then by score.


In the template code, we loop over the sorted_list and print the name, age, and score of each item.


How to use the sort filter in Jinja2?

To use the sort filter in Jinja2, you can follow these steps:

  1. Start by ensuring that you have imported Jinja2 and set up an environment:
1
2
3
4
from jinja2 import Environment, select_autoescape
env = Environment(
    autoescape=select_autoescape(['html', 'xml'])
)


  1. Next, define a template string or load the template from a file:
1
2
3
4
5
6
7
template_string = """
    {% for item in list | sort %}
        {{ item }}
    {% endfor %}
"""

template = env.from_string(template_string)


  1. Create a list of values to be sorted:
1
my_list = [5, 2, 8, 1, 9, 3]


  1. Render the template with the list using the render method:
1
output = template.render(list=my_list)


  1. The sort filter can be used within a loop to sort the list in ascending order. In the template, use the filter like this:
1
2
3
{% for item in list | sort %}
    {{ item }}
{% endfor %}


  1. Finally, print or use the output variable as desired:
1
print(output)


The output will be the sorted list printed one item per line:

1
2
3
4
5
6
1
2
3
5
8
9


You can modify the template according to your needs, but this basic example demonstrates how to use the sort filter in Jinja2.


How to sort a list of dates in Jinja2?

In Jinja2, you can use the sorted filter to sort a list of dates. However, since dates are usually represented as strings in Jinja2, you need to convert them into date objects before sorting.


Here's an example of how to sort a list of date strings in Jinja2:

  1. Define a custom Jinja2 filter called date to convert the date string into a date object. You can do this by using the datetime module:
1
2
3
4
from datetime import datetime

def date(string, format='%Y-%m-%d'):
    return datetime.strptime(string, format).date()


  1. Add the date filter to the Jinja2 environment:
1
2
3
4
from jinja2 import Environment

env = Environment()
env.filters['date'] = date


  1. In your Jinja2 template, use the sorted filter to sort the list of dates using the date filter:
1
2
3
{% for item in dates|sort(attribute='date') %}
    {{ item }}
{% endfor %}


Here, dates is the list of date strings that you want to sort.


Make sure to update the format parameter in the date filter if your date strings are in a different format.


Note: If you're using Jinja2 in a web framework like Flask, you can define the date filter directly in your Flask application or create a separate module to import and register the filter with the Jinja2 environment.

Facebook Twitter LinkedIn Telegram Pocket

Related Posts:

In Jinja2, you can mark strings as "safe" to prevent them from being escaped when rendered in a view or template. This is useful when you have a string that contains HTML or other special characters that you want to display as-is on the page.To mark a ...
In Jinja2, you can access part of a list using slicing, which allows you to extract a specific portion of the list. Slicing is done by specifying the start and end indexes within square brackets after the list variable.Here's an example of how to access pa...
Jinja2 is a widely used templating language in Python that allows you to generate dynamic content for web applications or other types of documents. When using Jinja2 templates, they are compiled into a more efficient representation in order to improve performa...