Skip to content
Myr

clean up engine comparisons

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parent ec50af3 · Browse files · 1 file+78 added−123 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+78 added−123 removed

  • other:+78 added−123 removed

1 file+78 added−123 removed

modified:docs/switching.rst+78 added-123 removed
1Switching from other Template Engines1Switching From Other Template Engines2=====================================34.. highlight:: html+jinja4This is a brief guide on some of the differences between Jinja syntax5and other template languages. See :doc:`/templates` for a comprehensive6guide to Jinja syntax and features.76If 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.810Jinja 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 bytes in a given encoding36 into unicode objects. This conversion is no longer implemented as it37 was inconsistent as most libraries are using the regular Python38 ASCII bytes to Unicode conversion. An application powered by Jinja 239 *has to* use unicode internally everywhere or make sure that Jinja 240 only 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.85869Django10------1112If you have previously worked with Django templates, you should find91Jinja very familiar. In fact, most of the syntax elements look and92work the same.13Jinja very familiar. Many of the syntax elements look and work the same.14However, Jinja provides some more syntax elements, and some work a bit15differently.1694However, Jinja provides some more syntax elements covered in the95documentation and some work a bit different.17This section covers the template changes. The API, including extension18support, is fundamentally different so it won't be covered here.1997This section covers the template changes. As the API is fundamentally98different we won't cover it here.20Django supports using Jinja as its template engine, see21https://docs.djangoproject.com/en/stable/topics/templates/#support-for-template-engines.222324Method Calls25~~~~~~~~~~~~26103In Django method calls work implicitly, while Jinja requires the explicit104Python syntax. Thus this Django code::27In Django, methods are called implicitly, without parentheses.2829.. code-block:: django3031 {% for page in user.get_created_pages %}32 ...33 {% endfor %}34110...looks like this in Jinja::35In Jinja, using parentheses is required for calls, like in Python. This36allows you to pass variables to the method, which is not possible37in Django. This syntax is also used for calling macros.3839.. code-block:: jinja4041 {% for page in user.get_created_pages() %}42 ...43 {% endfor %}44116This allows you to pass variables to the method, which is not possible in117Django. This syntax is also used for macros.4546Filter Arguments47~~~~~~~~~~~~~~~~48122Jinja provides more than one argument for filters. Also the syntax for123argument passing is different. A template that looks like this in Django::49In Django, one literal value can be passed to a filter after a colon.5051.. code-block:: django5253 {{ items|join:", " }}54127looks like this in Jinja::55In Jinja, filters can take any number of positional and keyword56arguments in parentheses, like function calls. Arguments can also be57variables instead of literal values.58129 {{ items|join(', ') }}59.. code-block:: jinja60131It is a bit more verbose, but it allows different types of arguments -132including variables - and more than one of them.61 {{ items|join(", ") }}626364Tests65~~~~~66137In addition to filters there also are tests you can perform using the is138operator. Here are some examples::67In addition to filters, Jinja also has "tests" used with the ``is``68operator. This operator is not the same as the Python operator.6970.. code-block:: jinja7172 {% if user.user_id is odd %}73 {{ user.username|e }} is odd74 {% else %}75 hmm. {{ user.username|e }} looks pretty normal
1 unmodified line
7778Loops79~~~~~80149For loops work very similarly to Django, but notably the Jinja special150variable for the loop context is called `loop`, not `forloop` as in Django.81In Django, the special variable for the loop context is called82``forloop``, and the ``empty`` is used for no loop items.83152In addition, the Django `empty` argument is called `else` in Jinja. For153example, the Django template::84.. code-block:: django8586 {% for item in items %}87 {{ item }}88 {% empty %}89 No items!90 {% endfor %}91161...looks like this in Jinja::92In Jinja, the special variable for the loop context is called ``loop``,93and the ``else`` block is used for no loop items.9495.. code-block:: jinja9697 {% for item in items %}164 {{ item }}98 {{ loop.index}}. {{ item }}99 {% else %}100 No items!101 {% endfor %}102103104Cycle105~~~~~106172The ``{% cycle %}`` tag does not exist in Jinja; however, you can achieve the173same output by using the `cycle` method on the loop context special variable.107In Django, the ``{% cycle %}`` can be used in a for loop to alternate108between values per loop.109175The following Django template::110.. code-block:: django111112 {% for user in users %}113 <li class="{% cycle 'odd' 'even' %}">{{ user }}</li>114 {% endfor %}115181...looks like this in Jinja::116In Jinja, the ``loop`` context has a ``cycle`` method.117118.. code-block:: jinja119120 {% for user in users %}121 <li class="{{ loop.cycle('odd', 'even') }}">{{ user }}</li>122 {% endfor %}123187There is no equivalent of ``{% cycle ... as variable %}``.124A cycler can also be assigned to a variable and used outside or across125loops with the ``cycle()`` global function.126127128Mako129----130193.. highlight:: html+mako131You can configure Jinja to look more like Mako:132195If you have used Mako so far and want to switch to Jinja you can configure196Jinja to look more like Mako:133.. code-block:: python134198.. sourcecode:: python135 env = Environment(136 block_start_string="<%",137 block_end_string="%>",138 variable_start_string="${",139 variable_end_string="}",140 comment_start_string="<%doc>",141 commend_end_string="</%doc>",142 line_statement_prefix="%",143 line_comment_prefix="##",144 )145200 env = Environment('<%', '%>', '${', '}', '<%doc>', '</%doc>', '%', '##')146With an environment configured like that, Jinja should be able to147interpret a small subset of Mako templates without any changes.148202With 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::149Jinja does not support embedded Python code, so you would have to move150that out of the template. You could either process the data with the151same code before rendering, or add a global function or filter to the152Jinja environment.153154The syntax for defs (which are called macros in Jinja) and template155inheritance is different too.156157The following Mako template:158159.. code-block:: mako160161 <%inherit file="layout.html" />162 <%def name="title()">Page Title</%def>163 <ul>164 % for item in list:165 <li>${item}</li>166 % endfor167 </ul>168216Looks like this in Jinja with the above configuration::169Looks like this in Jinja with the above configuration:170171.. code-block:: jinja172173 <% extends "layout.html" %>174 <% block title %>Page Title<% endblock %>175 <% block body %>176 <ul>
5 unmodified lines