How to determine debug mode in jinja?

Under the flask, I want to include / exclude material in the jinja template based on whether we are in debug mode or not. I am not discussing whether this is a good or bad idea (I would vote β€œbad”, but I want to do this only for this case, nevertheless :-), since this can happen?

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

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

not that it would be too complicated, but I would rather simply magically say in the template:

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

Is there some kind of default variable that just looks around waiting for me to pounce?

+5
source share
2 answers

use contextual processors

To automatically introduce new variables into the template context, context processors exist in Flask. Context processors are launched before the template is visualized and have the ability to enter new values ​​in the template context. A context processor is a function that returns a dictionary. The keys and values ​​of this dictionary are then combined with the template context for all templates in the application:

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

Now debug variable available in templates.

+8
source

When you launch the flash application using app.run(debug=True) , you can also just check the config object as follows:

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

Source: https://habr.com/ru/post/1232778/


All Articles