Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the Jinja environment variable in Flask?

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?

like image 430
Sarath Avatar asked Jun 02 '20 11:06

Sarath


People also ask

How do I set environment variable in Flask?

Similarly, the FLASK_ENV variable sets the environment on which we want our flask application to run. For example, if we put FLASK_ENV=development the environment will be switched to development. By default, the environment is set to development.

Does Flask need Jinja?

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.

What is app config [' Secret_key ']?

SECRET_KEY: Flask "secret keys" are random strings used to encrypt sensitive user data, such as passwords. Encrypting data in Flask depends on the randomness of this string, which means decrypting the same data is as simple as getting a hold of this string's value.


1 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
like image 132
Falc Avatar answered Oct 08 '22 07:10

Falc