def custom_sort(iterable, somearg):
    if iterable is None or isinstance(iterable, Undefined):
        return iterable
return iterable
env = Environment()
env.filters['customsort'] = custom_sort
Пользовательский фильтр jinja2 для итератора