【问题标题】:Flask partial view like MVC 3像 MVC 3 这样的烧瓶部分视图
【发布时间】:2012-01-23 12:51:19
【问题描述】:

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

【问题讨论】:

  • 你可以在一个函数中编写小部件代码,然后从视图中调用该函数,这还不够吗?
  • @Alex Morega 如何在jinja2视图模板中调用functin?
  • @magichui 你把它作为参数传递给 render_template...

标签: python flask


【解决方案1】:

有几种方法可以在 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 并根据几乎任何东西加载不同的模板。但对于这种情况,这肯定是矫枉过正。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 2012-05-15
    • 1970-01-01
    • 2013-06-08
    • 2015-06-20
    相关资源
    最近更新 更多