Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jinja2 print to console or logging

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?

like image 209
Javier Novoa C. Avatar asked Feb 09 '13 00:02

Javier Novoa C.


People also ask

What is Autoescape in Jinja2?

When autoescaping is enabled, Jinja2 will filter input strings to escape any HTML content submitted via template variables. Without escaping HTML input the application becomes vulnerable to Cross Site Scripting (XSS) attacks. Unfortunately, autoescaping is False by default.

How does Jinja templating work?

It is a text-based template language and thus can be used to generate any markup as well as source code. The Jinja template engine allows customization of tags, filters, tests, and globals. Also, unlike the Django template engine, Jinja allows the template designer to call functions with arguments on objects.


1 Answers

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!

like image 80
dmoreno Avatar answered Sep 22 '22 12:09

dmoreno