Jinja: Importing Specific Names from a Template
n
In Jinja2, the from ... import ... statement allows you to selectively import specific macros or variables from a template into the current namespace. This is a great alternative to importing the entire template module, as it helps to keep your template’s namespace clean and avoids potential naming conflicts. This method is often preferred when you only need one or two macros from a helper file.
nn
How It Works
n
The from ... import ... statement works by loading a template and pulling only the requested macros or variables directly into the current template’s scope. The syntax is {% from 'template_path' import macro_name, another_macro %}. You can also rename an imported macro using the as keyword, for example, {% from 'forms.html' import input as input_field %}. This is useful for avoiding conflicts if the macro name is the same as a variable in your current template.
nn
nn
Code Demonstration
n
Let’s assume we have a helper file named forms.html with macros for rendering form elements.
nn
forms.html (the imported module)
n
{% macro input(name, value='', type='text') -%}n <input type="{{ type }}" value="{{ value|e }}" name="{{ name }}">n{%- endmacro %}nn{%- macro textarea(name, value='', rows=10, cols=40) -%}n <textarea name="{{ name }}" rows="{{ rows }}" cols="{{ cols }}">{{ value|e }}</textarea>n{%- endmacro %}
n
Using from...import to access specific macros
n
{% from 'forms.html' import input as input_field, textarea %}n<dl>n <dt>Username</dt>n <dd>{{ input_field('username') }}</dd>n <dt>Password</dt>n <dd>{{ input_field('password', type='password') }}</dd>n</dl>n<p>{{ textarea('comment') }}</p>
n
In this example, we import both the `input` and `textarea` macros. We also use the `as` keyword to rename the `input` macro to `input_field`, demonstrating how to avoid naming conflicts. This provides a clear and concise way to use the macros directly without a namespace prefix.
n
Important Note: Macros and variables that start with one or more underscores are considered private and cannot be imported.
nn
n
n
