如何检测 jinja 中的调试模式?

How to detect debug mode in jinja?

在 flask 下,我想 include/exclude 根据我们是否处于调试模式在 jinja 模板中填充内容。我不是在争论这是好主意还是坏主意(我会投票 'bad',但仍然想针对这种情况这样做 :-),那么这怎么可能最好呢?

我希望我不必将变量显式传递到模板中,不像这样:

render_template('foo.html', debug=app.debug)

并不是说这太难了,但我宁愿在模板中神奇地说:

{% if debug %}
      go crazzzzy
{% endif %}

是不是有什么默认变量懒得等我扑过去?

使用context processors

To inject new variables automatically into the context of a template, context processors exist in Flask. Context processors run before the template is rendered and have the ability to inject new values into the template context. A context processor is a function that returns a dictionary. The keys and values of this dictionary are then merged with the template context, for all templates in the app:

@app.context_processor
def inject_debug():
    return dict(debug=app.debug)

现在 debug 变量可在模板中访问。

当您 运行 使用 app.run(debug=True) 的烧瓶应用程序时,您也可以像这样检查 config 对象:

{% if config['DEBUG'] %}
    <h1>My html here</h1>
{% endif %}