Import a Python module into a Jinja template?

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 %}

Leave a Comment