Skip to content
Myr

switching.rst

This file

Path

docs/switching.rst

226 lines · 6.9 KiB

Last changed by

use "Jinja" instead of "Jinja2"David Lordbefore adoption8182509

History of this file

Take it

1Switching from other Template Engines2=====================================34.. highlight:: html+jinja56If you have used a different template engine in the past and want to switch7to Jinja here is a small guide that shows the basic syntactic and semantic8changes between some common, similar text template engines for Python.910Jinja 111-------1213Jinja 2 is mostly compatible with Jinja 1 in terms of API usage and template14syntax.  The differences between Jinja 1 and 2 are explained in the following15list.1617API18~~~1920Loaders21    Jinja 2 uses a different loader API.  Because the internal representation22    of templates changed there is no longer support for external caching23    systems such as memcached.  The memory consumed by templates is comparable24    with regular Python modules now and external caching doesn't give any25    advantage.  If you have used a custom loader in the past have a look at26    the new :ref:`loader API <loaders>`.2728Loading templates from strings29    In the past it was possible to generate templates from a string with the30    default environment configuration by using `jinja.from_string`.  Jinja 231    provides a :class:`Template` class that can be used to do the same, but32    with optional additional configuration.3334Automatic unicode conversion35    Jinja 1 performed automatic conversion of bytestrings in a given encoding36    into unicode objects.  This conversion is no longer implemented as it37    was inconsistent as most libraries are using the regular Python ASCII38    bytestring to Unicode conversion.  An application powered by Jinja 239    *has to* use unicode internally everywhere or make sure that Jinja 2 only40    gets unicode strings passed.4142i18n43    Jinja 1 used custom translators for internationalization.  i18n is now44    available as Jinja 2 extension and uses a simpler, more gettext friendly45    interface and has support for babel.  For more details see46    :ref:`i18n-extension`.4748Internal methods49    Jinja 1 exposed a few internal methods on the environment object such50    as `call_function`, `get_attribute` and others.  While they were marked51    as being an internal method it was possible to override them.  Jinja 252    doesn't have equivalent methods.5354Sandbox55    Jinja 1 was running sandbox mode by default.  Few applications actually56    used that feature so it became optional in Jinja 2.  For more details57    about the sandboxed execution see :class:`SandboxedEnvironment`.5859Context60    Jinja 1 had a stacked context as storage for variables passed to the61    environment.  In Jinja 2 a similar object exists but it doesn't allow62    modifications nor is it a singleton.  As inheritance is dynamic now63    multiple context objects may exist during template evaluation.6465Filters and Tests66    Filters and tests are regular functions now.  It's no longer necessary67    and allowed to use factory functions.686970Templates71~~~~~~~~~7273Jinja 2 has mostly the same syntax as Jinja 1.  What's different is that74macros require parentheses around the argument list now.7576Additionally Jinja 2 allows dynamic inheritance now and dynamic includes.77The old helper function `rendertemplate` is gone now, `include` can be used78instead.  Includes no longer import macros and variable assignments, for79that the new `import` tag is used.  This concept is explained in the80:ref:`import` documentation.8182Another small change happened in the `for`-tag.  The special loop variable83doesn't have a `parent` attribute, instead you have to alias the loop84yourself.  See :ref:`accessing-the-parent-loop` for more details.858687Django88------8990If you have previously worked with Django templates, you should find91Jinja very familiar.  In fact, most of the syntax elements look and92work the same.9394However, Jinja provides some more syntax elements covered in the95documentation and some work a bit different.9697This section covers the template changes.  As the API is fundamentally98different we won't cover it here.99100Method Calls101~~~~~~~~~~~~102103In Django method calls work implicitly, while Jinja requires the explicit104Python syntax. Thus this Django code::105106    {% for page in user.get_created_pages %}107        ...108    {% endfor %}109110...looks like this in Jinja::111112    {% for page in user.get_created_pages() %}113        ...114    {% endfor %}115116This allows you to pass variables to the method, which is not possible in117Django. This syntax is also used for macros.118119Filter Arguments120~~~~~~~~~~~~~~~~121122Jinja provides more than one argument for filters.  Also the syntax for123argument passing is different.  A template that looks like this in Django::124125    {{ items|join:", " }}126127looks like this in Jinja::128129    {{ items|join(', ') }}130131It is a bit more verbose, but it allows different types of arguments -132including variables - and more than one of them.133134Tests135~~~~~136137In addition to filters there also are tests you can perform using the is138operator.  Here are some examples::139140    {% if user.user_id is odd %}141        {{ user.username|e }} is odd142    {% else %}143        hmm. {{ user.username|e }} looks pretty normal144    {% endif %}145146Loops147~~~~~148149For loops work very similarly to Django, but notably the Jinja special150variable for the loop context is called `loop`, not `forloop` as in Django.151152In addition, the Django `empty` argument is called `else` in Jinja. For153example, the Django template::154155    {% for item in items %}156        {{ item }}157    {% empty %}158        No items!159    {% endfor %}160161...looks like this in Jinja::162163    {% for item in items %}164        {{ item }}165    {% else %}166        No items!167    {% endfor %}168169Cycle170~~~~~171172The ``{% cycle %}`` tag does not exist in Jinja; however, you can achieve the173same output by using the `cycle` method on the loop context special variable.174175The following Django template::176177    {% for user in users %}178        <li class="{% cycle 'odd' 'even' %}">{{ user }}</li>179    {% endfor %}180181...looks like this in Jinja::182183    {% for user in users %}184        <li class="{{ loop.cycle('odd', 'even') }}">{{ user }}</li>185    {% endfor %}186187There is no equivalent of ``{% cycle ... as variable %}``.188189190Mako191----192193.. highlight:: html+mako194195If you have used Mako so far and want to switch to Jinja you can configure196Jinja to look more like Mako:197198.. sourcecode:: python199200    env = Environment('<%', '%>', '${', '}', '<%doc>', '</%doc>', '%', '##')201202With an environment configured like that, Jinja should be able to interpret203a small subset of Mako templates.  Jinja does not support embedded Python204code, so you would have to move that out of the template.  The syntax for defs205(which are called macros in Jinja) and template inheritance is different too.206The following Mako template::207208    <%inherit file="layout.html" />209    <%def name="title()">Page Title</%def>210    <ul>211    % for item in list:212        <li>${item}</li>213    % endfor214    </ul>215216Looks like this in Jinja with the above configuration::217218    <% extends "layout.html" %>219    <% block title %>Page Title<% endblock %>220    <% block body %>221    <ul>222    % for item in list:223        <li>${item}</li>224    % endfor225    </ul>226    <% endblock %>