Accessing Flask Session Variables in Jinja Templates


In Flask, the session object can be read (in the same manner as a dictionary) to retrieve data unique to the session. It's conveniently available in Jinja templates as well.

👇

from flask import render_template_string


@app.route('/get_email')
def get_email():
    return render_template_string("""
        {% if session['email'] %}
            <h1>Welcome {{ session['email'] }}!</h1>
        {% else %}
            <h1>Welcome! Please enter your email <a href="{{ url_for('set_email') }}">here.</a></h1>
        {% endif %}
    """)

For more, review Sessions in Flask.