pythontemplatesjinja2

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 ?


Solution

  • 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