Import a Python module into a Jinja template?

Matt Norris picture Matt Norris · Jan 28, 2011 · Viewed 40.7k times · Source

Is it possible to import a Python module into a Jinja template so I can use its functions?

For example, I have a format.py file that contains methods for formatting dates and times. In a Jinja macro, can I do something like the following?

{% from 'dates/format.py' import timesince %}

{% macro time(mytime) %}
<a title="{{ mytime }}">{{ timesince(mytime) }}</a>
{% endmacro %}

Because format.py is not a template, the code above gives me this error:

UndefinedError: the template 'dates/format.py' (imported on line 2 in 'dates/macros.html') does not export the requested name 'timesince'

...but I was wondering if there was another way to achieve this.

Answer

Wooble picture Wooble · Jan 28, 2011

Within the template, no, you cannot import python code.

The way to do this is to register the function as a jinja2 custom filter, like this:

In your python file:

from dates.format import timesince

environment = jinja2.Environment(whatever)
environment.filters['timesince'] = timesince
# render template here

In your template:

{% macro time(mytime) %}
<a title="{{ mytime }}">{{ mytime|timesince }}</a>
{% endmacro %}