Jinja

Differences To Django Templates

Navigation

Contents

If you have previously worked with Django templates, you should find Jinja very familiar. In fact, most of the syntax elements look and work the same.

However, Jinja provides some more syntax elements covered in the documentation and some work a bit different.

Method Calls

In Django method calls work implicitly. With Jinja you have to specify that you want to call an object. Thus this Django code:

{% for page in user.get_created_pages %}
  ...
{% endfor %}

will look like this in Jinja:

{% for page in user.get_created_pages() %}
  ...
{% endfor %}

This allows you to pass variables to the function which is also used for macros and loop recursion, both features that don't exist in Django.

Conditions

In Django you can use the following constructs to check for equality:

{% ifequals foo "bar" %}
    ...
{% else %}
    ...
{% endifequals %}

In Jinja you can use the normal if statement in combination with operators:

{% if foo == 'bar' %}
    ...
{% else %}
    ...
{% endif %}

You can also have multiple elif branches in your template:

{% if something %}
    ...
{% elif otherthing %}
    ...
{% elif foothing %}
    ...
{% else %}
    ...
{% endif %}

Filter Arguments

Jinja provides more than one argument for filters. Also the syntax for argument passing is different. A template that looks like this in Django:

{{ items|join:", " }}

looks like this in jinja:

{{ items|join(', ') }}

In fact it's a bit more verbose but it allows different types of arguments - including variables - and more than one of them.

Tests

In addition to filters there also are tests you can perform using the is operator. Here are some examples:

{% if user.user_id is odd %}
    {{ user.username|e }} is odd
{% else %}
    hmm. {{ user.username|e }} looks pretty normal
{% endif %}

For a list of supported tests head over to the syntax reference.