gpt4 book ai didi

python - 将 Python 模块导入 Jinja 模板?

转载 作者:IT老高 更新时间:2023-10-28 21:32:44 26 4
gpt4 key购买 nike

是否可以将 Python 模块导入 Jinja 模板以便我可以使用它的功能?

例如,我有一个 format.py 文件,其中包含格式化日期和时间的方法。在 Jinja 宏中,我可以执行以下操作 吗?

{% 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 custom filter ,像这样:

在你的 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 %}

关于python - 将 Python 模块导入 Jinja 模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4828406/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com