Sea*_*ira 27
有几种方法可以在Jinja2模板中包含内容:
该include语句将呈现提供的视图(默认情况下使用当前上下文):
{# In your_view_template.jinja #}
{# ... your code ... #}
{% include "widgets/your_widget.jinja" %}
{# ... your code ... #}
Run Code Online (Sandbox Code Playgroud)
{# In your_view_template.jinja #}
{% import "widgets/your_widget.jinja" as your_widget %}
{# ... your code ... #}
{{ you_widget.render(your, important, variables, etc.) }}
{# ... your code ... #}
Run Code Online (Sandbox Code Playgroud)
双方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
#}
Run Code Online (Sandbox Code Playgroud)
这些都与MVC的部分视图类似(至少,因为我了解它们)
或者,如果您的Widget需要访问ACL或信息不应该提供给样板层,你不能重新写你的观点乘虚而入include,并import可以采取@亚历克斯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 ... #}
Run Code Online (Sandbox Code Playgroud)
你甚至可以创建自己的模板加载器并根据几乎任何东西加载不同的模板.但对于这种情况来说,这肯定会有点过分.