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...
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?
3 Answers
I think you can achieve it using filters () or 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!
A similar but slightly different approach using context processor:
In python / flask:
@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 as follows:
{{ mdebug("any text or variable") }}
I would have an HTML element with an id set and the attribute of 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>