如何在Jinja2中包含具有相对路径的模板 [英] How to include a template with relative path in Jinja2
问题描述
我正在尝试在模板中包含另一个位于同一文件夹中的文件。为此,我只是做 {%import'header.jinja2'%}
。问题是我不断收到 TemplateNotFound
错误。
I'm trying, in a template, to include another one that is in the same folder. To do so, i'm just doing {% import 'header.jinja2' %}
. The problem is that i keep getting a TemplateNotFound
error.
我的模板文件夹看起来像
My template folder looks like
+ myProject
|
+--+ templates
|
+--+ arby
| |-- header.jinja2
| |-- footer.jinja2
| +-- base.jinja2
|
+--+ bico
|-- header.jinja2
|-- footer.jinja2
+-- base.jinja2
所以当我渲染arby的'base.jinja2'时,我想包含'arby / header.jinja2',当我渲染bico的'base.jinja2'时我想包括'bico / header.jinja2'。问题是我不想在{%include'arby / base.jinja2'%}中写'arby /'或'bico /'前缀。这可能吗?
So when I render arby's 'base.jinja2' I would like to include 'arby/header.jinja2' and when I render bico's 'base.jinja2' I would like to include 'bico/header.jinja2'. The thing is that I don't want to write the 'arby/' or 'bico/' prefix in the {% include 'arby/base.jinja2' %}. Is this possible?
谢谢
推荐答案
有提示有关子类化环境和覆盖的 jinja2.Environment.join_path()文档字符串join_path()方法支持 import
相对于当前(即join_path的 parent 参数)模板的路径。
There is a hint in the jinja2.Environment.join_path() docstring about subclassing Environment and overriding the join_path() method to support import
paths relative to the current (i.e., the parent argument of join_path) template.
以下是此类的示例:
class RelEnvironment(jinja2.Environment):
"""Override join_path() to enable relative template paths."""
def join_path(self, template, parent):
return os.path.join(os.path.dirname(parent), template)
这篇关于如何在Jinja2中包含具有相对路径的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!