Skip to content

Instantly share code, notes, and snippets.

@daymien
Last active July 24, 2019 09:22
Show Gist options
  • Save daymien/ab8afe4201255640b3cfb38f9026dc7f to your computer and use it in GitHub Desktop.
Save daymien/ab8afe4201255640b3cfb38f9026dc7f to your computer and use it in GitHub Desktop.
Jinja2 sort natural sort alphanum
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