Search code examples
pythontemplatesjinja2

How can I have a list of all the file used by a Jinja2 template?


I have a jinja2 template that uses other templates with include and extends statements. I would like to retrieve a list of all the templates that are involved in the construction of the template.

import jinja2
environment = jinja2.Environment()
template = environment.get_template("mynestedtemplate.html")
template.render(vartest="Hello")

I see only a function for listing the blocks:

jinja2Template.blocks 

Is there a way to list the templates used?


Solution

  • You can override the Environment.get_template method with a wrapper that stores the given template names into a list:

    class NameTrackingEnvironment(jinja2.Environment):
        def __init__(self, **kwargs):
            super().__init__(**kwargs)
            self.names = []
    
        def get_template(self, name, parent=None, globals=None):
            self.names.append(name)
            return super().get_template(name, parent, globals)
    

    so that given the following templates:

    base.html

    Greetings:
    {% block content %}{{ vartest }}{% endblock %}
    

    child.html

    World
    

    mynestedtemplate.html

    {% extends 'base.html' %}
    {% block content %}{{ super() }}, {% include 'child.html' %}!{% endblock %}
    

    the following code:

    environment = NameTrackingEnvironment(loader=jinja2.FileSystemLoader(''))
    template = environment.get_template('mynestedtemplate.html')
    print(template.render(vartest="Hello"))
    print(environment.names)
    

    would then output:

    Greetings:
    Hello, World!
    ['mynestedtemplate.html', 'base.html', 'child.html']
    

    Demo: https://replit.com/@blhsing/NavyAwfulCryptocurrency