简体   繁体   中英

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, !

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM