是否可以将Python模块导入Jinja模板,以便我可以使用其功能?
例如,我有一个 format.py 文件,其中包含用于格式化日期和时间的方法。在神社宏,我可以做一些 像 下面?
{% from 'dates/format.py' import timesince %} {% macro time(mytime) %} <a title="{{ mytime }}">{{ timesince(mytime) }}</a> {% endmacro %}
因为 format.py 不是模板,所以上面的代码给了我这个错误:
UndefinedError: the template 'dates/format.py' (imported on line 2 in 'dates/macros.html') does not export the requested name 'timesince'
…但是我想知道是否还有另一种方法可以实现这一目标。
在模板中,否,您不能导入python代码。
这样做的方法是将函数注册为jinja2定制过滤器,如下所示:
在您的python文件中:
from dates.format import timesince environment = jinja2.Environment(whatever) environment.filters['timesince'] = timesince # render template here
在您的模板中:
{% macro time(mytime) %} <a title="{{ mytime }}">{{ mytime|timesince }}</a> {% endmacro %}