Just for completeness...
Jinja has (at least?) two different ways of sorting the dictionaries. One is dictsort
and the other is sort
.
dictsort
{% for key, value in dictionary|dictsort %}
This way of doing it gives you the key, value
pairs directly, without .items()
, and sorts the dictionaries by key
.
sort
{% for key, value in dictionary.items()|sort(attribute="sort_by_?") %}
This way of doing it needs you to ask for the .items()
, just like standard python would. But, it lets you specify a somewhat custom way to sort them.
Within the attribute string (it needs to be a string) you can use 0
to reference the dictionary key
and 1
to reference the dictionary value
. If you want a specific inner key
that exists inside of that value
, you can access it by a .
(examples below).
Also, you can use jinja's |
stuff inside the attribute string if you need to convert strings to integers or whatever (it goes inside of the string).
sort examples
Sorting by value["name"]
{% for key, value in dictionary.items()|sort(attribute="1.name")%}
Sorting by key
(but the stupid way, since this would be the default if you don't specify any attribute)
{% for key, value in dictionary.items()|sort(attribute="0")%}
Sorting by int(key)
so that "10"
doesn't end up before "2"
when you have numbers stored as strings.
{% for key, value in dictionary.items()|sort(attribute="0|int")%}
{'xyz': {'name': 'A', 'is_sth': True}, 'abc': {'name': 'B', 'is_sth': True}}
– Angelikaangelina