[FIXED] How to set the Jinja environment variable in Flask?

Issue

I have a page with the following Code Structure:

Python Code:

from flask import Flask,render_template

app=Flask(__name__)

@app.route('/')
def home():
    return render_template("first.html")

@app.route('/second')
def next():
    return render_template("second.html")

if __name__=="__main__":
    app.run(debug=True)

HTML Code for second.html:

{% extends first.html %}
<dosomething>
</dosomething>

Now I want to set the Environment of Jinja as follows:

Environment:

import jinja2

JINJA_ENV=jinja2.Environment(block_start_string='#%',block_end_string="#%",variable_start_string='{',variable_end_string='}')

I want this changes to be reflected in Flask. Should this variable be initialized with Flask in some way or left as such?

Solution

It’s not publically documented, but a Flask() object has a .jinja_options dict that will be used to build the Jinja Environment. Just make sure to set it ASAP.

Source:

https://github.com/pallets/flask/blob/bbb273bb761461ab329f03ff2d9002f6cb81e2a4/src/flask/app.py#L272

https://github.com/pallets/flask/blob/bbb273bb761461ab329f03ff2d9002f6cb81e2a4/src/flask/app.py#L652

Example:

from flask import Flask
from jinja2 import ChainableUndefined

app = Flask(__name__)
app.jinja_options["undefined"] = ChainableUndefined

Answered By – Falc

Answer Checked By – Clifford M. (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published