Last active
July 24, 2019 09:22
-
-
Save daymien/ab8afe4201255640b3cfb38f9026dc7f to your computer and use it in GitHub Desktop.
Jinja2 sort natural sort alphanum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
from jinja2.filters import environmentfilter, make_attrgetter, ignore_case | |
@environmentfilter | |
def sort_alphanum(environment, value, reverse=False, case_sensitive=False, attribute=None): | |
""" | |
https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/ | |
Extended use in jinja2 | |
""" | |
key_func = make_attrgetter( | |
environment, attribute, | |
postprocess=ignore_case if not case_sensitive else None | |
) | |
convert = lambda t: int(t) if t.isdigit() else t | |
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key_func(key))] | |
return sorted(value, key=alphanum_key, reverse=reverse) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment