Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raise error for undefined attributes in Jinja templates in Flask

By default Flask renders empty values for undefined attributes in Jinja templates. I want to raise an error instead. How can I change this behavior in Flask?

Hello, {{ name }}!
render_template('index.html')
Hello, !
like image 830
estevo Avatar asked Aug 24 '16 15:08

estevo


People also ask

What is the difference between Jinja and Jinja2?

Jinja, also commonly referred to as "Jinja2" to specify the newest release version, is a Python template engine used to create HTML, XML or other markup formats that are returned to the user via an HTTP response.

Does Jinja template engine support Unicode?

Jinja is using Unicode internally which means that you have to pass Unicode objects to the render function or bytestrings that only consist of ASCII characters.


1 Answers

Change the Flask app's Jinja env's undefined class to be StrictUndefined.

from flask import Flask
from jinja2 import StrictUndefined

app = Flask(__name__)
app.jinja_env.undefined = StrictUndefined

If a template tries to use a variable that is undefined (except to test if it's undefined) it will raise an error.

Hello, {{ name }}!
render_template('index.html')
jinja2.exceptions.UndefinedError: 'name' is undefined
like image 144
estevo Avatar answered Sep 25 '22 03:09

estevo