Flask Jinja2 – How Does the ‘With’ Statement Work?

flaskjinja2python

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).

Best Answer

{% 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