有几种方法可以在 Jinja2 模板中包含内容:
include 语句将呈现提供的视图(默认使用当前上下文):
{# In your_view_template.jinja #}
{# ... your code ... #}
{% include "widgets/your_widget.jinja" %}
{# ... your code ... #}
你也可以在视图模板中定义macros和import:
{# In your_view_template.jinja #}
{% import "widgets/your_widget.jinja" as your_widget %}
{# ... your code ... #}
{{ you_widget.render(your, important, variables, etc.) }}
{# ... your code ... #}
import 和 include 都可以使用变量,所以这样的事情是可能的:
# In your view
if complex_conditions.are_true():
widget = "widgets/special_custom_widget.jinja"
else:
widget = "widgets/boring_widget.jinja"
render_template("your_view.jinja", widget=widget)
{# In your_view_template.jinja #}
{% include widget %}
{#
import widget as sidebar_widget
{{ sidebar_widget.render() }}
would also work
#}
这些都类似于 MVC 的局部视图(至少,就我的理解而言)
或者,如果您的小部件需要访问模板层不应使用的 ACL 或信息,并且您无法重写视图以利用 include 和 import,则可以使用 @[Alex Morega]的建议并将可调用对象作为变量传递给模板并在那里呈现。
# In your view
render_template("your_view.jinja", widget=you_callable, etc, etc, etc)
{# In your_view_template.jinja #}
{# ... your code ... #}
{{ widget() }}
{# Or, if you are returning HTML that is not a Markup construct #}
{{ widget() | safe }}
{# ... your code ... #}
您甚至可以创建自己的template loader 并根据几乎任何东西加载不同的模板。但对于这种情况,这肯定是矫枉过正。