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).
According to jinja.pocoo.org/docs/dev/extensions/#with-extension "with" in Jinja2 templates sets up a variable scope. When you close with "with", the variable you define there stops existing. This is like "dtml-with" in a Zope template, not like "with" in a Python context manager.
Flask leverages Jinja2 as its template engine. You are obviously free to use a different template engine, but you still have to install Jinja2 to run Flask itself. This requirement is necessary to enable rich extensions. An extension can depend on Jinja2 being present.
Flask comes packaged with Jinja2, and hence we just need to install Flask. For this series, I recommend using the development version of Flask, which includes much more stable command line support among many other features and improvements to Flask in general.
Delimiters Used in Jinja 2 1. {% %} : used for control statements such as loops and if-else statements. 2. {{ }} :These double curly braces are the widely used tags in a template file and they are used for embedding variables and ultimately printing their value during code execution.
{% 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With