【问题标题】:How does the 'with' statement work in Flask (Jinja2)?'with' 语句在 Flask (Jinja2) 中是如何工作的?
【发布时间】:2015-04-09 21:19:57
【问题描述】:

在 Python 中,您可以像这样使用 with 语句 (source):

class controlled_execution:
    def __enter__(self):
        # set things up
        return thing
    def __exit__(self, type, value, traceback):
        # tear things down

with controlled_execution() as thing:
     # some code

在 Flask/Jinja2 中,使用 flash 消息的标准过程如下(source):

{% with messages = get_flashed_messages() %}
  {% if messages %}
    {% for message in messages %}
      <!-- do stuff with `message` -->
    {% endfor %}        
  {% endif %}
{% endwith %}

我想知道{% with messages = get_flashed_messages() %} 在语法方面的工作原理。

我未能在纯 Python 中重新创建它:

  • with messages = get_flashed_messages(): pass 提高 SyntaxError
  • with get_flashed_messages() as messages: pass 提高 AttributeError: __exit__

(在这两种情况下,我都从flask 导入了get_flashed_messages)。

【问题讨论】:

    标签: python flask jinja2


    【解决方案1】:

    Jinja 中的{% with %} 语句允许您定义变量,但使用{% endwith %} 限制变量的范围

    声明。例如:

    {% with myvar=1 %}
    ...
    {% endwith %} 
    

    在正文中声明的任何元素都可以访问 myvar 变量。

    请参考 - https://www.webforefront.com/django/usebuiltinjinjastatements.html

    【讨论】:

    • with 在 django 中的烧瓶中不起作用。在烧瓶中使用{% set myvar=1 %}
    【解决方案2】:

    Flask 中的 with 语句与 Python 中的 with 语句不同。

    在 python 中,等价物是这样的:

    messages = get_flashed_messages()
    

    【讨论】:

    • 谢谢。但是它们到底有什么不同呢? Flask-with 在语法上改变了 Python-with 还是不同的东西?另外:我认为{% 和 `%} 之间的代码是 100% Python 代码。
    • 它们是完全不同的东西,它们只是共享名称,但除此之外,它们是完全不同的野兽。大多数情况下,{%%} 之间的所有内容都类似于 Python,但并不完全。
    • 根据Jinja2模板中的jinja.pocoo.org/docs/dev/extensions/#with-extension "with" 设置一个变量作用域。当您使用“with”关闭时,您在此处定义的变量将停止存在。这就像 Zope 模板中的“dtml-with”,而不像 Python 上下文管理器中的“with”。
    猜你喜欢
    • 1970-01-01
    • 2011-08-26
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 2019-04-04
    相关资源
    最近更新 更多