将Python模块导入Jinja模板吗? [英] Import a Python module into a Jinja template?
问题描述
是否可以将Python模块导入Jinja模板,以便我可以使用其功能?
Is it possible to import a Python module into a Jinja template so I can use its functions?
例如,我有一个 format.py 文件,其中包含用于格式化日期和时间的方法.在Jinja宏中,我可以做以下类似 的事情吗?
For example, I have a format.py file that contains methods for formatting dates and times. In a Jinja macro, can I do something like the following?
{% from 'dates/format.py' import timesince %}
{% macro time(mytime) %}
<a title="{{ mytime }}">{{ timesince(mytime) }}</a>
{% endmacro %}
由于 format.py 不是模板,因此上面的代码给了我这个错误:
Because format.py is not a template, the code above gives me this error:
UndefinedError: the template 'dates/format.py' (imported on line 2 in 'dates/macros.html') does not export the requested name 'timesince'
...但是我想知道是否还有另一种方法可以实现这一目标.
...but I was wondering if there was another way to achieve this.
推荐答案
在模板中,否,您无法导入python代码.
Within the template, no, you cannot import python code.
执行此操作的方法是将功能注册为jinja2 自定义过滤器,如下所示:
The way to do this is to register the function as a jinja2 custom filter, like this:
在您的python文件中:
In your python file:
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 %}
这篇关于将Python模块导入Jinja模板吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!