Sergei Basharov
Sergei Basharov

Reputation: 53940

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?

Upvotes: 28

Views: 15933

Answers (2)

patb
patb

Reputation: 1816

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:

        <meta name="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.

Upvotes: 29

PartialOrder
PartialOrder

Reputation: 2960

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')
def quoted(s):
    l = re.findall('\'([^\']*)\'', str(s))
    if l:
        return l[0]
    return None

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

Upvotes: 8

Related Questions