Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 559
pawelswiecki Avatar asked Apr 09 '15 21:04

pawelswiecki


People also ask

What is with in Jinja?

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.

How do you use a Jinja2 Flask?

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.

Does Jinja2 have Flask?

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.

What are the delimiters used in Jinja2 template?

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.


1 Answers

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

like image 86
Shraddha Avatar answered Sep 19 '22 13:09

Shraddha