switching.rst 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. Switching from other Template Engines
  2. =====================================
  3. .. highlight:: html+jinja
  4. If you have used a different template engine in the past and want to swtich
  5. to Jinja2 here is a small guide that shows the basic syntatic and semantic
  6. changes between some common, similar text template engines for Python.
  7. Jinja1
  8. ------
  9. Jinja2 is mostly compatible with Jinja1 in terms of API usage and template
  10. syntax. The differences between Jinja1 and 2 are explained in the following
  11. list.
  12. API
  13. ~~~
  14. Loaders
  15. Jinja2 uses a different loader API. Because the internal representation
  16. of templates changed there is no longer support for external caching
  17. systems such as memcached. The memory consumed by templates is comparable
  18. with regular Python modules now and external caching doesn't give any
  19. advantage. If you have used a custom loader in the past have a look at
  20. the new :ref:`loader API <loaders>`.
  21. Loading templates from strings
  22. In the past it was possible to generate templates from a string with the
  23. default environment configuration by using `jinja.from_string`. Jinja2
  24. provides a :class:`Template` class that can be used to do the same, but
  25. with optional additional configuration.
  26. Automatic unicode conversion
  27. Jinja1 performed automatic conversion of bytestrings in a given encoding
  28. into unicode objects. This conversion is no longer implemented as it
  29. was inconsistent as most libraries are using the regular Python ASCII
  30. bytestring to Unicode conversion. An application powered by Jinja2
  31. *has to* use unicode internally everywhere or make sure that Jinja2 only
  32. gets unicode strings passed.
  33. i18n
  34. Jinja1 used custom translators for internationalization. i18n is now
  35. available as Jinja2 extension and uses a simpler, more gettext friendly
  36. interface and has support for babel. For more details see
  37. :ref:`i18n-extension`.
  38. Internal methods
  39. Jinja1 exposed a few internal methods on the environment object such
  40. as `call_function`, `get_attribute` and others. While they were marked
  41. as being an internal method it was possible to override them. Jinja2
  42. doesn't have equivalent methods.
  43. Sandbox
  44. Jinja1 was running sandbox mode by default. Few applications actually
  45. used that feature so it became optional in Jinja2. For more details
  46. about the sandboxed execution see :class:`SandboxedEnvironment`.
  47. Context
  48. Jinja1 had a stacked context as storage for variables passed to the
  49. environment. In Jinja2 a similar object exists but it doesn't allow
  50. modifications nor is it a singleton. As inheritance is dynamic now
  51. multiple context objects may exist during template evaluation.
  52. Filters and Tests
  53. Filters and tests are regular functions now. It's no longer necessary
  54. and allowed to use factory functions.
  55. Templates
  56. ~~~~~~~~~
  57. Jinja2 has mostly the same syntax as Jinja1. What's different is that
  58. macros require parentheses around the argument list now.
  59. Additionally Jinja2 allows dynamic inheritance now and dynamic includes.
  60. The old helper function `rendertemplate` is gone now, `include` can be used
  61. instead. Includes no longer import macros and variable assignments, for
  62. that the new `import` tag is used. This concept is explained in the
  63. :ref:`import` documentation.
  64. Another small change happened in the `for`-tag. The special loop variable
  65. doesn't have a `parent` attribute, instead you have to alias the loop
  66. yourself. See :ref:`accessing-the-parent-loop` for more details.
  67. Django
  68. ------
  69. If you have previously worked with Django templates, you should find
  70. Jinja2 very familiar. In fact, most of the syntax elements look and
  71. work the same.
  72. However, Jinja2 provides some more syntax elements covered in the
  73. documentation and some work a bit different.
  74. This section covers the template changes. As the API is fundamentally
  75. different we won't cover it here.
  76. Method Calls
  77. ~~~~~~~~~~~~
  78. In Django method calls work implicitly. With Jinja2 you have to specify that
  79. you want to call an object. Thus this Django code::
  80. {% for page in user.get_created_pages %}
  81. ...
  82. {% endfor %}
  83. will look like this in Jinja::
  84. {% for page in user.get_created_pages() %}
  85. ...
  86. {% endfor %}
  87. This allows you to pass variables to the function which is also used for macros
  88. which is not possible in Django.
  89. Conditions
  90. ~~~~~~~~~~
  91. In Django you can use the following constructs to check for equality::
  92. {% ifequal foo "bar" %}
  93. ...
  94. {% else %}
  95. ...
  96. {% endifequal %}
  97. In Jinja2 you can use the normal if statement in combination with operators::
  98. {% if foo == 'bar' %}
  99. ...
  100. {% else %}
  101. ...
  102. {% endif %}
  103. You can also have multiple elif branches in your template::
  104. {% if something %}
  105. ...
  106. {% elif otherthing %}
  107. ...
  108. {% elif foothing %}
  109. ...
  110. {% else %}
  111. ...
  112. {% endif %}
  113. Filter Arguments
  114. ~~~~~~~~~~~~~~~~
  115. Jinja2 provides more than one argument for filters. Also the syntax for
  116. argument passing is different. A template that looks like this in Django::
  117. {{ items|join:", " }}
  118. looks like this in Jinja2::
  119. {{ items|join(', ') }}
  120. In fact it's a bit more verbose but it allows different types of arguments -
  121. including variables - and more than one of them.
  122. Tests
  123. ~~~~~
  124. In addition to filters there also are tests you can perform using the is
  125. operator. Here are some examples::
  126. {% if user.user_id is odd %}
  127. {{ user.username|e }} is odd
  128. {% else %}
  129. hmm. {{ user.username|e }} looks pretty normal
  130. {% endif %}
  131. Loops
  132. ~~~~~
  133. For loops work very similar to Django, the only incompatibility is that in
  134. Jinja2 the special variable for the loop context is called `loop` and not
  135. `forloop` like in Django.
  136. Cycle
  137. ~~~~~
  138. The ``{% cycle %}`` tag does not exist in Jinja because of it's implicit
  139. nature. However you can achieve mostly the same by using the `cycle`
  140. method on a loop object.
  141. The following Django template::
  142. {% for user in users %}
  143. <li class="{% cycle 'odd' 'even' %}">{{ user }}</li>
  144. {% endfor %}
  145. Would look like this in Jinja::
  146. {% for user in users %}
  147. <li class="{{ loop.cycle('odd', 'even') }}">{{ user }}</li>
  148. {% endfor %}
  149. There is no equivalent of ``{% cycle ... as variable %}``.
  150. Mako
  151. ----
  152. .. highlight:: html+mako
  153. If you have used Mako so far and want to switch to Jinja2 you can configure
  154. Jinja2 to look more like Mako:
  155. .. sourcecode:: python
  156. env = Environment('<%', '%>', '${', '}', '%')
  157. Once the environment is configure like that Jinja2 should be able to interpret
  158. a small subset of Mako templates. Jinja2 does not support embedded Python code
  159. so you would have to move that out of the template. The syntax for defs (in
  160. Jinja2 defs are called macros) and template inheritance is different too. The
  161. following Mako template::
  162. <%inherit file="layout.html" />
  163. <%def name="title()">Page Title</%def>
  164. <ul>
  165. % for item in list:
  166. <li>${item}</li>
  167. % endfor
  168. </ul>
  169. Looks like this in Jinja2 with the above configuration::
  170. <% extends "layout.html" %>
  171. <% block title %>Page Title<% endblock %>
  172. <% block body %>
  173. <ul>
  174. % for item in list:
  175. <li>${item}</li>
  176. % endfor
  177. </ul>
  178. <% endblock %>