jinja2 从模板加载模板文件
有没有办法可以从另一个模板文件中加载 jinja2 模板?比如
{{ render_template('path/to/file.html') }}
我有一些我想重用的片段,所以拥有这个功能对我来说很重要。
Is there a way I can load a jinja2 template from within another template file? Something like
{{ render_template('path/to/file.html') }}
I have some snippets which I want to reuse, so it's important for me to have this functionality.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
{% include "file" %}
就是这样做的。有关更多信息,请参阅 jinja2 文档。{% include "file" %}
does this. See the jinja2 docs for more information.使用
extends
标记或include
标记,具体取决于您想要如何设计多文件视图。Use either the
extends
tag or theinclude
tag, depending on how you want to design your multi-file views.您应该使用
{% macro -%}
制作模板文件,并使用{% import "file" as file %}
来使用其他模板文件中的宏。请参阅文档。这是一个示例:
具体来说,这个答案允许OP将参数传递给他的宏,类似于他想要的行为,例如 render_template 的行为方式(简单地包含文件,如前面的答案所述,并不能实现与 render_template 相同的行为)。
这通常比为每个习惯用法创建一个新模板或使用继承更好,继承是一种特殊情况的解决方案(如果您想在一个模板中多次使用该片段怎么办)?
You should make template files with
{% macro -%}
s and use{% import "file" as file %}
to use the macros in other template files. See the docs.Here is an example:
Specifically this answer allows the OP to pass arguments to his macros, similar to the behavior he desired like how render_template behaves (simply including the file as previous answers have stated above does not achieve the same behavior as render_template).
This is generally better than making a fresh template for every idiom, or than using inheritance, which is a special case solution (what if you want to use the snippet multiple times in one template)?