Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect debug mode in jinja?

Under flask, I want to include/exclude stuff in the jinja template based upon whether, or not, we are in debug mode. I'm not debating if this is a good, or bad, idea (i'd vote 'bad' but want to do it just for this case nonetheless :-), so how might this best happen?

I was hoping i would not have to pass the variable explicitly into the template, unlike this:

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

not that this would be too hard, but I'd rather just magically say in the template:

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

Is there some default variable just lazing about waiting for me to pounce?

like image 698
John Mee Avatar asked Oct 02 '15 09:10

John Mee


2 Answers

use 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)

now debug variable accessible in templates.

like image 123
r-m-n Avatar answered Nov 17 '22 11:11

r-m-n


When you run your flask application with app.run(debug=True), you can also just check the config object like so:

{% if config['DEBUG'] %}
    <h1>My html here</h1>
{% endif %}
like image 42
GabeMeister Avatar answered Nov 17 '22 11:11

GabeMeister