How does the 'with' statement work in Flask (Jinja2)?

旧城冷巷雨未停 提交于 2019-12-19 18:54:25

问题


In Python you can use the with statement like this (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

In Flask/Jinja2, the standard procedure for using flash messages is the following (source):

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

I'd like to know how {% with messages = get_flashed_messages() %} works in terms of syntax.

I failed to recreate it in pure Python:

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

(I've imported get_flashed_messages from flask in both cases).


回答1:


The with statement in Flask is not the same as the with statement in Python.

Within python the equivalent would be this:

messages = get_flashed_messages()



回答2:


{% with %} statement in Jinja lets you define variable, but limits the scope of a variable with the {% endwith %}

 statement. For example :

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

Any elements declared in the body will have access to the myvar variable.

Please, refer - https://www.webforefront.com/django/usebuiltinjinjastatements.html



来源:https://stackoverflow.com/questions/29549259/how-does-the-with-statement-work-in-flask-jinja2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!