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?

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!

2

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest