jinja2 print to console or logging

Javier Novoa C. picture Javier Novoa C. · Feb 9, 2013 · Viewed 23.6k times · Source

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

Since Jinja2 templates may have logic inside, I think it would be useful sometimes to log some info in to some kind of logfile, or at least get printed to console.

Is this possible or am I just talking garbage?

Answer

dmoreno picture dmoreno · Feb 9, 2013

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

Not tested but the filter should be something like:

def debug(text):
  print text
  return ''

environment.filters['debug']=debug

To be used as:

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

Remember to remove the debug on production code!