Skip to content Skip to sidebar Skip to footer

How To Get File Name Of Current Template Inside Jinja2 Template?

Say I use return render_template('index.html', users=users). Is it possible to get the filename inside a template without explicit sending of it inside the view?

Solution 1:

Although undocumented, {{ self._TemplateReference__context.name }} will give the template name. And there are a number of interresting attributes that you can use after self._TemplateReference__context.

You could, for example, add this to your topmost base template:

<metaname="template"content="{{ self._TemplateReference__context.name }}">

So that looking at a page source will help you quickly find the relevant template file. If you don't want to expose this kind of information, make it conditional to testing environment.

Solution 2:

If all you need is the basename, you can use {{ self }} which will return a repr string containing the basename of the template, e.g., <TemplateReference 'view.html'>. You could parse this with a filter, e.g., {{ self | quoted }}

@app.template_filter('quoted')defquoted(s):
    l = re.findall('\'([^\']*)\'', str(s))
    if l:
        return l[0]
    returnNone

If you need the full path, e.g., '/full/path/to/view.html' you may want to subclass Template.

Post a Comment for "How To Get File Name Of Current Template Inside Jinja2 Template?"