Stable sorting in Jinja2

2024/11/3 7:45:05

It is possible to apply the sort filter in Jinja2 successively to sort a list first by one attribute, then by another? This seems like a natural thing to do, but in my testing, the preceeding sort is completely unstable and all sorting is lost.

I already worked around it by sorting first in python before passing the list to the template, but I would like to know if it's possible to sort "stable" in Jinja2.

The way I applied the filter was like so:

{{ item_list|sort(attribute='value')|sort(attribute='color') }}

What I had hoped to see was the list sorted by color, with the elements sharing a color sorted by value. Instead, it looked the same as if the value sort never happened.

For example, from this list:

2 red
3 blue
3 red
2 blue
1 blue
4 red

I would like something like this:

1 blue
2 blue
3 blue
2 red
3 red
4 red

I looked at the groupby filter but that implementation seems too complicated (would require nested for loops).

Answer

I am not aware of a native jinja2 filter that can do this. To sort a list based on multiple attributes,you can define a custom filter in jinja2.

From the accepted answer to this question, you can write your own filter

import operatordef sort_multi(L,*operators): L.sort(key=operator.itemgetter(*operators))return L

Register it in your application environment. So for pyramid, you would do something like

env = config.get_jinja2_environment()
env.filters['sort_multi'] = sort_multi

And finally in your templates

{{item_list|sort_multi('value','color')}}
https://en.xdnf.cn/q/73174.html

Related Q&A

Factor to complex roots using sympy

I cant figure out how to factor an polynomial expression to its complex roots.>>> from sympy import * >>> s = symbol(s) >>> factor(s**2+1)2 s + 1

Using multiple custom classes with Pipeline sklearn (Python)

I try to do a tutorial on Pipeline for students but I block. Im not an expert but Im trying to improve. So thank you for your indulgence. In fact, I try in a pipeline to execute several steps in prepar…

Python equivalent of pointers

In python everything works by reference:>>> a = 1 >>> d = {a:a} >>> d[a] 1 >>> a = 2 >>> d[a] 1I want something like this>>> a = 1 >>> d =…

Pip is broken, gives PermissionError: [WinError 32]

I installed the python-certifi-win32 module (Im so busy trying to fix this problem that I dont even remember why I originally installed it). Right after I installed it, though, I started getting this e…

Pandas highlight rows based on index name

I have been struggling with how to style highlight pandas rows based on index names. I know how to highlight selected rows but when I have to highlight based on the index, the code is not working.Setup…

Histogram of sum instead of count using numpy and matplotlib

I have some data with two columns per row. In my case job submission time and area.I have used matplotlibs hist function to produce a graph with time binned by day on the x axis, and count per day on t…

Find subsequences of strings within strings

I want to make a function which checks a string for occurrences of other strings within them. However, the sub-strings which are being checked may be interrupted within the main string by other letters…

How to bestow string-ness on my class?

I want a string with one additional attribute, lets say whether to print it in red or green.Subclassing(str) does not work, as it is immutable. I see the value, but it can be annoying.Can multiple inhe…

How to pass Python instance to C++ via Python/C API

Im extending my library with Python (2.7) by wrapping interfaces with SWIG 2.0, and have a graph object in which I want to create a visitor. In C++, the interface looks like this:struct Visitor{virtua…

REST API in Python with FastAPI and pydantic: read-only property in model

Assume a REST API which defines a POST method on a resource /foos to create a new Foo. When creating a Foo the name of the Foo is an input parameter (present in the request body). When the server creat…