Custom jinja2 filter for iterator

假如想象 提交于 2019-12-01 01:24:25

问题


How do I most efficiently write a custom filter for Jinja2 that applies to an iterable like the built-in 'sort' filter, for use in a for loop in the template?

For example:

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

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


回答1:


The same way you'd write any other filter. Here's an example that should get you started:

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

Don't worry about efficiency until it becomes a problem. The template engine is unlikely to be the bottle-neck in any case.



来源:https://stackoverflow.com/questions/5481205/custom-jinja2-filter-for-iterator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!