mnieber
mnieber

Reputation: 1030

How to show Jinja2 top level template code?

I'm using Jinja2 with a custom loader that creates (complex) templates dynamically. This means that error messages do not contain a template filename but instead refer to the "top-level template code". To inspect errors, I would like to print the top level template code to the console (for example by calling render in a try-catch block). How can this be achieved?

Upvotes: 0

Views: 214

Answers (1)

mnieber
mnieber

Reputation: 1030

One (not so elegant) way to achieve this is to cache all responses of the custom loader:

import os

_template_by_fn = dict()


def print_template(template_fn):
    print("Template: %s" % template_fn)
    print(os.linesep.join(_template_by_fn[str(template_fn)]))


def custom_load_template(template_fn):
    # Do work to create the template.
    template_code = ""
    # When done, cache the result.
    _template_by_fn[str(template_fn)] = template_code

    return template_code

Upvotes: 0

Related Questions