Jinja2是否支持模板相对路径,例如%(here)s/other/template.html,包含相对于当前模板在文件系统中的位置的其他模板?
Wil*_*hen 37
我不相信.通常,您通过指定相对于您正在使用的任何模板加载器和环境的根的路径来包含或扩展其他模板.
所以,假设您的模板全部存在,/path/to/templates并且您已经设置了Jinja,如下所示:
import jinja2
template_dir = '/path/to/templates'
loader = jinja2.FileSystemLoader(template_dir)
environment = jinja2.Environment(loader=loader)
Run Code Online (Sandbox Code Playgroud)
现在,如果您想要包含/path/to/templates/includes/sidebar.html在/path/to/templates/index.html模板中,您可以在以下内容中编写以下内容index.html:
{% include 'includes/sidebar.html' %}
Run Code Online (Sandbox Code Playgroud)
和Jinja会想出如何找到它.
rob*_*ing 16
只是为了添加Will McCutchen的答案,
您可以在加载器中拥有多个目录.然后它在每个目录中搜索(按顺序),直到找到模板.
例如,如果您想要"sidebar.html"而不是"/includes/sidebar.html",那么请:
loader=jinja2.FileSystemLoader(
[os.path.join(os.path.dirname(__file__),"templates/includes"),
os.path.join(os.path.dirname(__file__),"templates")])
Run Code Online (Sandbox Code Playgroud)
代替
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__),"templates"))
Run Code Online (Sandbox Code Playgroud)
根据jinja2.Environment.join_path()的文档,通过重写join_path()来实现"模板路径连接",可以支持相对模板路径.
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)
Run Code Online (Sandbox Code Playgroud)