Jinja2 custom filter for iterator

What is the most efficient way to write a custom filter for Jinja2 that applies to iterable, like the built-in filter 'sort', for use in a for loop in a template?

For instance:

{% for item in iterable|customsort(somearg) %} ... {% endfor %} 

See http://jinja.pocoo.org/docs/api/#writing-filters for general documentation

+6
python jinja2
source share
1 answer

Similarly, you should write any other filter. Here is an example that should run you:

 from jinja2 import Environment, Undefined def custom_sort(iterable, somearg): if iterable is None or isinstance(iterable, Undefined): return iterable # Do custom sorting of iterable here return iterable # ... env = Environment() env.filters['customsort'] = custom_sort 

Do not worry about efficiency until it becomes a problem. In any case, the pattern mechanism is unlikely to be a bottleneck.

+13
source share

All Articles