迭代器的自定义jinja2过滤器 [英] Custom jinja2 filter for iterator

查看:46
本文介绍了迭代器的自定义jinja2过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何最有效地为Jinja2编写一个自定义过滤器,该过滤器适用于像内置"sort"过滤器这样的可迭代对象,以便在模板的for循环中使用?

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 item in iterable|customsort(somearg) %}
...
{% endfor %}

请参见 http://jinja.pocoo.org/docs/api/#writing -过滤器用于常规文档

推荐答案

与编写其他任何过滤器的方式相同.这是一个应该帮助您入门的示例:

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.

这篇关于迭代器的自定义jinja2过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆