user2302957
user2302957

Reputation:

Python and Jinja2 - Import template of another environment

I am trying to build a project that uses Jinja2 tempalting. I would like to have a sort of template library that I could import in many other projects. The problem I have is that I can't find a way to include/import a template from this library from within the template of my project.

As an example, we could use the same example that we find in Jinja2 documentation here

File forms.html

{% macro input(name, value='', type='text') -%}
<input type="{{ type }}" value="{{ value|e }}" name="{{ name }}">
{%- endmacro %}

ProjectPage.html

{% import 'forms.html' as forms %}
<dl>
    <dt>Username</dt>
    <dd>{{ forms.input('username') }}</dd>
    <dt>Password</dt>
    <dd>{{ forms.input('password', type='password') }}</dd>
</dl>

This example would works since the "forms.html" template is in the same environment as "ProjectPage.html". Since I can use the macro in many projects, I would like to put it inside a module that I could import later. Doing so, makes the macro template in a different environment and the import statement fails.

Hwo can I make this work ?

Upvotes: 2

Views: 951

Answers (2)

HeyMan
HeyMan

Reputation: 1865

This worked for me:

from package1 import jinja_env
from package2 import my_jinja_env

await my_jinja_env.get_template("buttongroup.htm").render_async(
    ...
    jinja_env=jinja_env,
)

then I can acces the jinja_env inside my_jinja_env in js:

{% from jinja_env.get_template('buttons.inc.htm') import render_button %}

Upvotes: 0

user2302957
user2302957

Reputation:

Well, I ended up finding a solution not so long after posting my question. Turns out it is quite easy.

It looks like we can pass variables to an environment using the globals attribute. We can also make an import statement on a template object.

So I pass my library environment to my project environment and I can call get_template from my project template.

env.globals['mylib'] = jinja2.Environment(loader=jinja2.PackageLoader('mylib', 'templates'))

Then in my template :

{% import mylib.get_template('folder1/theTemplate.tpl') as mytemplate %}

Good day

Upvotes: 3

Related Questions