How to set the Jinja environment variable in Flask?

Question:

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?

Asked By: Sarath

||

Answers:

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

You can also pass in an entire Jinja Environment like this:

from flask import Flask
from jinja2 import Environment

app = Flask(__name__)
app.jinja_env = Environment(...)
Answered By: colelemonz
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.