3

I am trying to build a dependency graph from a render of a template and I am running into a bit of trouble trying to get good information out of jinja.

I want to be able to render a template and get back a list/set of all of the files that were used to render the template. For example:

# template.html
{% extend base.html %}
{% for partial in partials %}
    {% include partial %}
{% endfor %}

And have it render and find out what files were used.

# deps.py
base_path = os.path.dirname(os.path.realpath(__file__))
jinja_env = jinja2.Environment(
    loader=jinja2.FileSystemLoader(base_path))

template = jinja_env.get_template('template.html')
template.render({
    "partials": [
        "test1.html",
        "test2.html",
    ],
})
# ???
looking_for = ['base.html', 'test1.html', 'test2.html']

I have checked out the AST tree and meta.find_referenced_templates(ast) but it only works when using a constant string for the include path.

Tried a custom extension looking at the tokens, but that has the same issues where I can see the variable name, but cannot get the values of the variable since it is done during the parsing/compiling phase.

Also tried overriding the {% include %} but wasn't sure how to do this correctly.

By using a custom loader I could get the values, but only if they have not been loaded before since the environment caches the loaded templates. (This solution may work if I disable the caching but then it has significant performance impact on rendering.)

How can I keep track of all the extend/include dependencies that are used for a single template render?

Randy
  • 445
  • 5
  • 9

0 Answers0