pallets / jinja

A very fast and expressive template engine.

Home Page:https://jinja.palletsprojects.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Force numeric sorting if text attributes contain numbers

martin3000 opened this issue · comments

commented

Very often, object attributes contain numbers which are put inside strings. If you sort them, they are sorted as text.
print(jinja2.Template("{{ x|sort|list }}").render(x=["1", "200", "33.3","h","100", "2", "10"]))
results in ['1', '10', '100', '2', '200', '33.3', 'h']

If you want to treat strings as numbers, it would be useful to have a switch for that:
print(jinja2.Template("{{ x|sort(numbers=True)|list }}").render(x=["1", "200", "33.3","h","100", "2", "10"]))
results in ['h', '1', '2', '10', '33.3', '100', '200']

I already created a patch for this feature.
See src/jinja2/filters.py

Thanks, but I don't plan to add this to the existing filter. You can write a custom filter if you need custom behavior, or pre-process your data in Python first.