Reputation: 33901
I'm looking for a way to have separate 'template'
and 'includes'
directories with Jinja2 and only allow
For example say I have the following directory layout:
/templates/
base.html
/includes/
header.html
footer.html
I'd like to ensure that the application level get_template
only has base.html
visible to it, and that the include
template statement only has header.html
and footer.html
available to it.
I'm aware that I can add both directories to the loader, eg:
loader = jinja2.FileSystemLoader(['/templates/', '/includes/'])
env = jinja2.Environment(loader=loader)
template = env.get_template('base.html')
But this doesn't give me the strict separation of the two different template types that I'm looking for.
Is there any way to enforce this separation, so that .get_template('base.html')
will succeed, but {% include 'base.html' %}
will fail?
Is there some way I can use two different loaders, one to get the template initially, and a second that'll be used when rendering that template?
For example, could I do something like this?...
base_loader = jinja2.FileSystemLoader('/templates/')
includes_loader = jinja2.FileSystemLoader('/includes/')
base_env = jinja2.Environment(loader=base_loader)
includes_env = jinja2.Environment(loader=includes_loader)
template = env.get_template('base.html')
template.env = includes_env
Upvotes: 3
Views: 1358
Reputation: 33901
The template
instance has an environment
property, so it looks like it's possible to do this...
base_loader = jinja2.FileSystemLoader('/templates/')
includes_loader = jinja2.FileSystemLoader('/includes/')
base_env = jinja2.Environment(loader=base_loader)
includes_env = jinja2.Environment(loader=includes_loader)
template = base_env.get_template('base.html')
template.environment = includes_env
This should ensure that only files in the /includes/
directory are available to the {% include ... %}
template statement.
Edit: changed env to base_env in line 7 of the code.
Upvotes: 1