问题
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
raisesSyntaxError
with get_flashed_messages() as messages: pass
raisesAttributeError: __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