Transition to Jinja templates from Django templates
If you're accustomed to using Django templates, this section describes the finer details you need to be aware of when using Jinja templates, such as: what Django template knowledge you can leverage in Jinja templates, what works differently in Jinja templates compared to Django templates and what are new things you need to learn that you'll come to appreciate in Jinja templates.
If you've never used Django templates, you can skip to the next section on Jinja template configuration in Django, as most of what follows is intended for experienced Django template users.
What works the same way in Jinja and Django templates
Just because Jinja is an entirely different template engine, doesn't mean it's radically different from Django's built-in template engine. You can expect to use the same approach for: Variables & blocks, conditionals & loops, comments, as well as spacing & special characters.
Variables and blocks
Curly braces {}
are
broadly used in Jinja templates just like they're used in Django
templates. To output a variable in Jinja you use the same
{{myvariable}}
syntax. Similarly, you also name blocks
to inherit snippets between templates with the {% block
footer %} {% endblock %}
syntax. In addition, Jinja also
uses the same Django {% extends "base.html" %}
syntax
to create parent/child relationships between templates.
Conditionals and loops
Jinja uses the same Django syntax
to create conditionals: {% if variable %}{% elif
othervariable %}{% else %}{% endif %}
. In addition, Jinja
also uses the same for loop syntax as Django: {% for item in
listofitems %}{{item}}{% endfor %}
.
Comments
Jinja also uses the same comment
tag as Django: {# This is a template comment that isn't
rendered #}
. However, note Jinja uses the {# #}
tag for both single and multi-line comments.
Spacing and special characters
Since Jinja templates were
inspired from Django templates, Jinja uses a similar approach to
dealing with spacing and special characters. For example, things
like spacing filters (e.g.center
and
wordwrap
) and special character handling
(e.g.safe
and escape
filters ) work the
same way in Jinja templates as they do in Django templates.
What works differently in Jinja templates compared to Django templates
However, not everything works the same way in Jinja templates, here are some Django template techniques you'll need to relearn to work with Jinja templates.
The remaining content for Django 4.0 is only available with a subscription.