Raise error for undefined attributes in Jinja templates in Flask

穿精又带淫゛_ 提交于 2020-01-03 16:49:22

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/39127940/raise-error-for-undefined-attributes-in-jinja-templates-in-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!