Does the Jinja2 templating language have the concept of 'here' (current directory)?

Viewed 34259

Does Jinja2 support template-relative paths e.g. %(here)s/other/template.html, to include other templates relative to the current template's place in the filesystem?

4 Answers

I do not believe so. Typically you include or extend other templates by specifying their paths relative to the root of whatever template loader and environment you're using.

So let's say your templates are all in /path/to/templates and you've set up Jinja like so:

import jinja2
template_dir = '/path/to/templates'
loader = jinja2.FileSystemLoader(template_dir)
environment = jinja2.Environment(loader=loader)

Now, if you'd like to include /path/to/templates/includes/sidebar.html in the /path/to/templates/index.html template, you'd write the following in your index.html:

{% include 'includes/sidebar.html' %}

and Jinja would figure out how to find it.

Just to add to Will McCutchen's answer,

You can have multiple directories in your loader. It then searches in each of the directories (in order) until it finds the template.

for example, if you wanted to have "sidebar.html" instead of "/includes/sidebar.html" then have:

loader=jinja2.FileSystemLoader(
        [os.path.join(os.path.dirname(__file__),"templates/includes"),
         os.path.join(os.path.dirname(__file__),"templates")])

instead of

loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__),"templates"))
Related