Skip to content
Myr

switching.rst

This file

Path

docs/switching.rst

242 lines · 7.2 KiB

Last changed by

Documented differences of cycling between Django and Jinja2.Armin Ronacherbefore adoptionf288b7a

History of this file

Take it

documentation updateArmin Ronacherbefore adoption5cdc1ac

lines 1–64why, one step back
1Switching from other Template Engines
2=====================================34.. highlight:: html+jinja56If you have used a different template engine in the past and want to swtich7to Jinja2 here is a small guide that shows the basic syntatic and semantic8changes between some common, similar text template engines for Python.910Jinja111------1213Jinja2 is mostly compatible with Jinja1 in terms of API usage and template14syntax. The differences between Jinja1 and 2 are explained in the following15list.1617API18~~~1920Loaders21 Jinja2 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`. Jinja231 provides a :class:`Template` class that can be used to do the same, but32 with optional additional configuration.3334Automatic unicode conversion35 Jinja1 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 Jinja239 *has to* use unicode internally everywhere or make sure that Jinja2 only40 gets unicode strings passed.4142i18n43 Jinja1 used custom translators for internationalization. i18n is now44 available as Jinja2 extension and uses a simpler, more gettext friendly45 interface and has support for babel. For more details see46 :ref:`i18n-extension`.4748Internal methods49 Jinja1 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. Jinja252 doesn't have equivalent methods.5354Sandbox55 Jinja1 was running sandbox mode by default. Few applications actually56 used that feature so it became optional in Jinja2. For more details57 about the sandboxed execution see :class:`SandboxedEnvironment`.5859Context60 Jinja1 had a stacked context as storage for variables passed to the61 environment. In Jinja2 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.64

added a function to parse assign targes and documented it for the extension interfaceArmin Ronacherbefore adoption09c002e

lines 65–68why, one step back
65Filters and Tests
66 Filters and tests are regular functions now. It's no longer necessary67 and allowed to use factory functions.68

documentation updateArmin Ronacherbefore adoption5cdc1ac

lines 69–72why, one step back
69
70Templates71~~~~~~~~~72

some small documentation fixesArmin Ronacherbefore adoption2b22874

lines 73–74why, one step back
73Jinja2 has mostly the same syntax as Jinja1. What's different is that
74macros require parentheses around the argument list now.

documentation updateArmin Ronacherbefore adoption5cdc1ac

line 75why, one step back
75

some small documentation fixesArmin Ronacherbefore adoption2b22874

lines 76–78why, one step back
76Additionally Jinja2 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, for

documentation updateArmin Ronacherbefore adoption5cdc1ac

lines 79–81why, one step back
79that the new `import` tag is used. This concept is explained in the
80:ref:`import` documentation.81

improved thread safety of the LRUCache and fixed a bug in for loopsArmin Ronacherbefore adoptione224488

lines 82–85why, one step back
82Another small change happened in the `for`-tag. The special loop variable
83doesn't have a `parent` attribute, instead you have to alias the loop84yourself. See :ref:`accessing-the-parent-loop` for more details.85

documentation updateArmin Ronacherbefore adoption5cdc1ac

lines 86–123why, one step back
86
87Django88------8990If you have previously worked with Django templates, you should find91Jinja2 very familiar. In fact, most of the syntax elements look and92work the same.9394However, Jinja2 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. With Jinja2 you have to specify that104you want to call an object. Thus this Django code::105106 {% for page in user.get_created_pages %}107 ...108 {% endfor %}109 110will look like this in Jinja::111112 {% for page in user.get_created_pages() %}113 ...114 {% endfor %}115116This allows you to pass variables to the function which is also used for macros117which is not possible in Django.118119Conditions120~~~~~~~~~~121122In Django you can use the following constructs to check for equality::123

Automated merge with ssh://team@pocoo.org/jinja2-mainArmin Ronacherbefore adoptiona11366e

line 124why, one step back
124 {% ifequal foo "bar" %}

documentation updateArmin Ronacherbefore adoption5cdc1ac

lines 125–127why, one step back
125 ...
126 {% else %}127 ...

Automated merge with ssh://team@pocoo.org/jinja2-mainArmin Ronacherbefore adoptiona11366e

line 128why, one step back
128 {% endifequal %}

documentation updateArmin Ronacherbefore adoption5cdc1ac

lines 129–176why, one step back
129
130In Jinja2 you can use the normal if statement in combination with operators::131132 {% if foo == 'bar' %}133 ...134 {% else %}135 ...136 {% endif %}137138You can also have multiple elif branches in your template::139140 {% if something %}141 ...142 {% elif otherthing %}143 ...144 {% elif foothing %}145 ...146 {% else %}147 ...148 {% endif %}149150Filter Arguments151~~~~~~~~~~~~~~~~152153Jinja2 provides more than one argument for filters. Also the syntax for154argument passing is different. A template that looks like this in Django::155156 {{ items|join:", " }}157158looks like this in Jinja2::159160 {{ items|join(', ') }}161162In fact it's a bit more verbose but it allows different types of arguments -163including variables - and more than one of them.164165Tests166~~~~~167168In addition to filters there also are tests you can perform using the is169operator. Here are some examples::170171 {% if user.user_id is odd %}172 {{ user.username|e }} is odd173 {% else %}174 hmm. {{ user.username|e }} looks pretty normal175 {% endif %}176

some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47

lines 177–183why, one step back
177Loops
178~~~~~179180For loops work very similar to Django, the only incompatibility is that in181Jinja2 the special variable for the loop context is called `loop` and not182`forloop` like in Django.183

Documented differences of cycling between Django and Jinja2.Armin Ronacherbefore adoptionf288b7a

lines 184–204why, one step back
184Cycle
185~~~~~186187The ``{% cycle %}`` tag does not exist in Jinja because of it's implicit188nature. However you can achieve mostly the same by using the `cycle`189method on a loop object.190191The following Django template::192193 {% for user in users %}194 <li class="{% cycle 'odd' 'even' %}">{{ user }}</li>195 {% endfor %}196197Would look like this in Jinja::198199 {% for user in users %}200 <li class="{{ loop.cycle('odd', 'even') }}">{{ user }}</li>201 {% endfor %}202203There is no equivalent of ``{% cycle ... as variable %}``.204

documentation updateArmin Ronacherbefore adoption5cdc1ac

lines 205–242why, one step back
205
206Mako207----208209.. highlight:: html+mako210211If you have used Mako so far and want to switch to Jinja2 you can configure212Jinja2 to look more like Mako:213214.. sourcecode:: python215216 env = Environment('<%', '%>', '${', '}', '%')217218Once the environment is configure like that Jinja2 should be able to interpret219a small subset of Mako templates. Jinja2 does not support embedded Python code220so you would have to move that out of the template. The syntax for defs (in221Jinja2 defs are called macros) and template inheritance is different too. The222following Mako template::223224 <%inherit file="layout.html" />225 <%def name="title()">Page Title</%def>226 <ul>227 % for item in list:228 <li>${item}</li>229 % endfor230 </ul>231232Looks like this in Jinja2 with the above configuration::233234 <% extends "layout.html" %>235 <% block title %>Page Title<% endblock %>236 <% block body %>237 <ul>238 % for item in list:239 <li>${item}</li>240 % endfor241 </ul>242 <% endblock %>