Jinja2 print for console or logging

I'm kind of new to Jinja2, and I wonder if there is a way to make templates, being generated, to print to the console or redirect some output to some stream?

Since Jinja2 templates can have logic inside, I think it would be useful sometimes to write some information to some kind of log file, or at least print to the console.

Is this possible or am I just saying trash?

+11
source share
3 answers

I think you can achieve this using filters ( http://jinja.pocoo.org/docs/api/#custom-filters ) or extensions ( http://jinja.pocoo.org/docs/extensions/#adding- extensions ). The idea is to simply print the filter or extension directly on the console.

Not tested, but the filter should look something like this:

def debug(text): print text return '' environment.filters['debug']=debug 

Used as:

 ...<p>Hello world!</p> {{"debug text!"|debug}}... 

Remember to remove debugging of production code!

+12
source

A similar but slightly different approach using the context processor:

In python / bulb:

 @app.context_processor def utility_functions(): def print_in_console(message): print str(message) return dict(mdebug=print_in_console) 

In jinja2, use it anywhere:

 {{ mdebug("any text or variable") }} 
+7
source

I would like to have an HTML element with an identifier set and an attribute hidden for the element. Then use JavaScript as such

 <p id="hidden-p">{{a_variable}}</p> <script> var hiddenP = document.getElementById("hidden-p").innerHTML; console.log(hiddenP); </script> 
0
source

All Articles