Flask局部视图如MVC 3

时间:2012-01-23 12:51:20

标签: python flask

是否有类似.net MVC 3的部分视图?
我想在一个视图页面中嵌入一个小部件,该小部件有自己的逻辑。

1 个答案:

答案 0 :(得分:24)

有几种方法可以在Jinja2模板中包含内容:

include语句将呈现提供的视图(默认情况下使用当前上下文):

{# In your_view_template.jinja #}
{# ... your code ... #}
{% include "widgets/your_widget.jinja" %}
{# ... your code ... #}

您还可以将macrosimport定义到视图模板中:

{# In your_view_template.jinja #}
{% import "widgets/your_widget.jinja" as your_widget %}
{# ... your code ... #}
{{ you_widget.render(your, important, variables, etc.) }}
{# ... your code ... #}

importinclude都可以使用变量,所以这样的事情是可能的:

# 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或信息,并且您无法重新编写视图以利用includeimport,则可以使用@ [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并根据几乎任何加载不同的模板。但对于这种情况来说,这肯定会有点过分。