Jinja2 Control Structure: The dictsort Filter
n
dictsort filter is designed for this exact purpose, allowing you to easily sort a dictionary’s items before iterating over them.nn
nn
n
How It Works
nThe dictsort filter takes a dictionary and returns a sorted list of its key-value pairs. By default, it sorts the items alphabetically by **key**. The output of this filter is a list of tuples, where each tuple contains a key and its corresponding value. This sorted list can then be used directly in a `for` loop to display your data in a predictable order.nnThe dictsort filter can also take additional arguments to customize the sorting behavior:n
- n
- Sorting by Value: To sort by value instead of key, pass the argument `true` to the filter (e.g., `my_dict | dictsort(true)`).
- Reverse Order: To sort in reverse or descending order, pass the argument `true` as the second parameter (e.g., `my_dict | dictsort(false, true)`).
n
n
n
Syntax
n
{% for key, value in my_dict | dictsort %}n <!-- Code to repeat for each sorted key-value pair -->n{% endfor %}
nn
nn
n
Demonstration with Code Samples
nHere are some practical examples of how to use the dictsort filter in a Jinja2 application.n
1. Sorting by Key
nThis is the default behavior of the dictsort filter. It is used to generate a definition list (<dl>) with the dictionary items sorted alphabetically by key.nnJinja2 Templaten
{% set my_dict = {'b': 'value for b', 'c': 'value for c', 'a': 'value for a'} %}n<dl>n{% for key, value in my_dict | dictsort %}n <dt>{{ key|e }}</dt>n <dd>{{ value|e }}</dd>n{% endfor %}n</dl>
nExplanation: Even though the `a` key appears last in the dictionary definition, the `dictsort` filter ensures that the output is sorted alphabetically, resulting in the order `a`, `b`, `c`. The `for` loop then iterates over this sorted list to create the HTML elements.nn
nn
n
2. Sorting by Value and in Reverse Order
nThis example demonstrates how to use the optional arguments to sort the dictionary items by their values instead of their keys, and also to display them in descending order.nnJinja2 Templaten
{% set scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78} %}n<p>High Scores:</p>n<ul>n{% for name, score in scores | dictsort(false, true) %}n <li><strong>{{ name }}</strong>: {{ score }}</li>n{% endfor %}n</ul>
nExplanation: In this code, we sort the `scores` dictionary by its values (`false`) and in reverse order (`true`), which effectively sorts the players from the highest score to the lowest. The `for` loop then renders an ordered list of high scores.nn
n
