18

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, !
davidism
  • 121,510
  • 29
  • 395
  • 339
estevo
  • 941
  • 11
  • 11

1 Answers1

25

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
davidism
  • 121,510
  • 29
  • 395
  • 339
estevo
  • 941
  • 11
  • 11
  • 8
    For those using jinja directly (rather than via Flask): You can pass `StrictUndefined` to the `Environment` constructor: `Environment(loader=..., autoescape=..., undefined=StrictUndefined)` – Arthur Tacca Sep 15 '20 at 14:02
  • And here is how to check for (TL;DR: `var is defined` ): https://stackoverflow.com/questions/3842690/in-jinja2-how-do-you-test-if-a-variable-is-undefined - this works even if the variable is undefined and strict undefined in place. – Roman Susi Apr 25 '23 at 05:48