templates.rst 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. Twig for Template Designers
  2. ===========================
  3. This document describes the syntax and semantics of the template engine and
  4. will be most useful as reference to those creating Twig templates.
  5. Synopsis
  6. --------
  7. A template is simply a text file. It can generate any text-based format (HTML,
  8. XML, CSV, LaTeX, etc.). It doesn't have a specific extension, ``.html`` or
  9. ``.xml`` are just fine.
  10. A template contains **variables** or **expressions**, which get replaced with
  11. values when the template is evaluated, and **tags**, which control the logic
  12. of the template.
  13. Below is a minimal template that illustrates a few basics. We will cover the
  14. details later on:
  15. .. code-block:: html+jinja
  16. <!DOCTYPE html>
  17. <html>
  18. <head>
  19. <title>My Webpage</title>
  20. </head>
  21. <body>
  22. <ul id="navigation">
  23. {% for item in navigation %}
  24. <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
  25. {% endfor %}
  26. </ul>
  27. <h1>My Webpage</h1>
  28. {{ a_variable }}
  29. </body>
  30. </html>
  31. There are two kinds of delimiters: ``{% ... %}`` and ``{{ ... }}``. The first
  32. one is used to execute statements such as for-loops, the latter prints the
  33. result of an expression to the template.
  34. IDEs Integration
  35. ----------------
  36. Many IDEs support syntax highlighting and auto-completion for Twig:
  37. * *Textmate* via the `Twig bundle`_
  38. * *Vim* via the `Jinja syntax plugin`_
  39. * *Netbeans* via the `Twig syntax plugin`_
  40. * *PhpStorm* (native as of 2.1)
  41. * *Eclipse* via the `Twig plugin`_
  42. * *Sublime Text* via the `Twig bundle`_
  43. * *GtkSourceView* via the `Twig language definition`_ (used by gedit and other projects)
  44. Variables
  45. ---------
  46. The application passes variables to the templates you can mess around in the
  47. template. Variables may have attributes or elements on them you can access
  48. too. How a variable looks like heavily depends on the application providing
  49. those.
  50. You can use a dot (``.``) to access attributes of a variable (methods or
  51. properties of a PHP object, or items of a PHP array), or the so-called
  52. "subscript" syntax (``[]``):
  53. .. code-block:: jinja
  54. {{ foo.bar }}
  55. {{ foo['bar'] }}
  56. .. note::
  57. It's important to know that the curly braces are *not* part of the
  58. variable but the print statement. If you access variables inside tags
  59. don't put the braces around.
  60. If a variable or attribute does not exist you will get back a ``null`` value.
  61. .. sidebar:: Implementation
  62. For convenience sake ``foo.bar`` does the following things on the PHP
  63. layer:
  64. * check if ``foo`` is an array and ``bar`` a valid element;
  65. * if not, and if ``foo`` is an object, check that ``bar`` is a valid property;
  66. * if not, and if ``foo`` is an object, check that ``bar`` is a valid method
  67. (even if ``bar`` is the constructor - use ``__construct()`` instead);
  68. * if not, and if ``foo`` is an object, check that ``getBar`` is a valid method;
  69. * if not, and if ``foo`` is an object, check that ``isBar`` is a valid method;
  70. * if not, return a ``null`` value.
  71. ``foo['bar']`` on the other hand only works with PHP arrays:
  72. * check if ``foo`` is an array and ``bar`` a valid element;
  73. * if not, return a ``null`` value.
  74. .. note::
  75. If you want to get a dynamic attribute on a variable, use the
  76. :doc:`attribute<functions/attribute>` function instead.
  77. Global Variables
  78. ~~~~~~~~~~~~~~~~
  79. The following variables are always available in templates:
  80. * ``_self``: references the current template;
  81. * ``_context``: references the current context;
  82. * ``_charset``: references the current charset.
  83. Setting Variables
  84. ~~~~~~~~~~~~~~~~~
  85. You can assign values to variables inside code blocks. Assignments use the
  86. :doc:`set<tags/set>` tag:
  87. .. code-block:: jinja
  88. {% set foo = 'foo' %}
  89. {% set foo = [1, 2] %}
  90. {% set foo = {'foo': 'bar'} %}
  91. Filters
  92. -------
  93. Variables can be modified by **filters**. Filters are separated from the
  94. variable by a pipe symbol (``|``) and may have optional arguments in
  95. parentheses. Multiple filters can be chained. The output of one filter is
  96. applied to the next.
  97. The following example removes all HTML tags from the ``name`` and title-cases
  98. it:
  99. .. code-block:: jinja
  100. {{ name|striptags|title }}
  101. Filters that accept arguments have parentheses around the arguments. This
  102. example will join a list by commas:
  103. .. code-block:: jinja
  104. {{ list|join(', ') }}
  105. To apply a filter on a section of code, wrap it with the
  106. :doc:`filter<tags/filter>` tag:
  107. .. code-block:: jinja
  108. {% filter upper %}
  109. This text becomes uppercase
  110. {% endfilter %}
  111. Go to the :doc:`filters<filters/index>` page to learn more about the built-in
  112. filters.
  113. Functions
  114. ---------
  115. Functions can be called to generate content. Functions are called by their
  116. name followed by parentheses (``()``) and may have arguments.
  117. For instance, the ``range`` function returns a list containing an arithmetic
  118. progression of integers:
  119. .. code-block:: jinja
  120. {% for i in range(0, 3) %}
  121. {{ i }},
  122. {% endfor %}
  123. Go to the :doc:`functions<functions/index>` page to learn more about the
  124. built-in functions.
  125. Control Structure
  126. -----------------
  127. A control structure refers to all those things that control the flow of a
  128. program - conditionals (i.e. ``if``/``elseif``/``else``), ``for``-loops, as
  129. well as things like blocks. Control structures appear inside ``{% ... %}``
  130. blocks.
  131. For example, to display a list of users provided in a variable called
  132. ``users``, use the :doc:`for<tags/for>` tag:
  133. .. code-block:: jinja
  134. <h1>Members</h1>
  135. <ul>
  136. {% for user in users %}
  137. <li>{{ user.username|e }}</li>
  138. {% endfor %}
  139. </ul>
  140. The :doc:`if<tags/if>` tag can be used to test an expression:
  141. .. code-block:: jinja
  142. {% if users|length > 0 %}
  143. <ul>
  144. {% for user in users %}
  145. <li>{{ user.username|e }}</li>
  146. {% endfor %}
  147. </ul>
  148. {% endif %}
  149. Go to the :doc:`tags<tags/index>` page to learn more about the built-in tags.
  150. Comments
  151. --------
  152. To comment-out part of a line in a template, use the comment syntax ``{# ...
  153. #}``. This is useful for debugging or to add information for other template
  154. designers or yourself:
  155. .. code-block:: jinja
  156. {# note: disabled template because we no longer use this
  157. {% for user in users %}
  158. ...
  159. {% endfor %}
  160. #}
  161. Including other Templates
  162. -------------------------
  163. The :doc:`include<tags/include>` tag is useful to include a template and
  164. return the rendered content of that template into the current one:
  165. .. code-block:: jinja
  166. {% include 'sidebar.html' %}
  167. Per default included templates are passed the current context.
  168. The context that is passed to the included template includes variables defined
  169. in the template:
  170. .. code-block:: jinja
  171. {% for box in boxes %}
  172. {% include "render_box.html" %}
  173. {% endfor %}
  174. The included template ``render_box.html`` is able to access ``box``.
  175. The filename of the template depends on the template loader. For instance, the
  176. ``Twig_Loader_Filesystem`` allows you to access other templates by giving the
  177. filename. You can access templates in subdirectories with a slash:
  178. .. code-block:: jinja
  179. {% include "sections/articles/sidebar.html" %}
  180. This behavior depends on the application embedding Twig.
  181. Template Inheritance
  182. --------------------
  183. The most powerful part of Twig is template inheritance. Template inheritance
  184. allows you to build a base "skeleton" template that contains all the common
  185. elements of your site and defines **blocks** that child templates can
  186. override.
  187. Sounds complicated but is very basic. It's easiest to understand it by
  188. starting with an example.
  189. Let's define a base template, ``base.html``, which defines a simple HTML
  190. skeleton document that you might use for a simple two-column page:
  191. .. code-block:: html+jinja
  192. <!DOCTYPE html>
  193. <html>
  194. <head>
  195. {% block head %}
  196. <link rel="stylesheet" href="style.css" />
  197. <title>{% block title %}{% endblock %} - My Webpage</title>
  198. {% endblock %}
  199. </head>
  200. <body>
  201. <div id="content">{% block content %}{% endblock %}</div>
  202. <div id="footer">
  203. {% block footer %}
  204. &copy; Copyright 2011 by <a href="http://domain.invalid/">you</a>.
  205. {% endblock %}
  206. </div>
  207. </body>
  208. </html>
  209. In this example, the :doc:`{% block %}<tags/block>` tags define four blocks
  210. that child templates can fill in. All the ``block`` tag does is to tell the
  211. template engine that a child template may override those portions of the
  212. template.
  213. A child template might look like this:
  214. .. code-block:: jinja
  215. {% extends "base.html" %}
  216. {% block title %}Index{% endblock %}
  217. {% block head %}
  218. {{ parent() }}
  219. <style type="text/css">
  220. .important { color: #336699; }
  221. </style>
  222. {% endblock %}
  223. {% block content %}
  224. <h1>Index</h1>
  225. <p class="important">
  226. Welcome on my awesome homepage.
  227. </p>
  228. {% endblock %}
  229. The :doc:`{% extends %}<tags/extends>` tag is the key here. It tells the
  230. template engine that this template "extends" another template. When the
  231. template system evaluates this template, first it locates the parent. The
  232. extends tag should be the first tag in the template.
  233. Note that since the child template doesn't define the ``footer`` block, the
  234. value from the parent template is used instead.
  235. It's possible to render the contents of the parent block by using the
  236. :doc:`parent<functions/parent>` function. This gives back the results of the
  237. parent block:
  238. .. code-block:: jinja
  239. {% block sidebar %}
  240. <h3>Table Of Contents</h3>
  241. ...
  242. {{ parent() }}
  243. {% endblock %}
  244. .. tip::
  245. The documentation page for the :doc:`extends<tags/extends>` tag describes
  246. more advanced features like block nesting, scope, dynamic inheritance, and
  247. conditional inheritance.
  248. HTML Escaping
  249. -------------
  250. When generating HTML from templates, there's always a risk that a variable
  251. will include characters that affect the resulting HTML. There are two
  252. approaches: manually escaping each variable or automatically escaping
  253. everything by default.
  254. Twig supports both, automatic escaping is enabled by default.
  255. .. note::
  256. Automatic escaping is only supported if the *escaper* extension has been
  257. enabled (which is the default).
  258. Working with Manual Escaping
  259. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  260. If manual escaping is enabled it's **your** responsibility to escape variables
  261. if needed. What to escape? If you have a variable that *may* include any of
  262. the following chars (``>``, ``<``, ``&``, or ``"``) you **have to** escape it
  263. unless the variable contains well-formed and trusted HTML. Escaping works by
  264. piping the variable through the :doc:`escape<filters/escape>` or ``e`` filter:
  265. .. code-block:: jinja
  266. {{ user.username|e }}
  267. {{ user.username|e('js') }}
  268. Working with Automatic Escaping
  269. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  270. Whether automatic escaping is enabled or not, you can mark a section of a
  271. template to be escaped or not by using the :doc:`autoescape<tags/autoescape>`
  272. tag:
  273. .. code-block:: jinja
  274. {% autoescape true %}
  275. Everything will be automatically escaped in this block
  276. {% endautoescape %}
  277. Escaping
  278. --------
  279. It is sometimes desirable or even necessary to have Twig ignore parts it would
  280. otherwise handle as variables or blocks. For example if the default syntax is
  281. used and you want to use ``{{`` as raw string in the template and not start a
  282. variable you have to use a trick.
  283. The easiest way is to output the variable delimiter (``{{``) by using a variable
  284. expression:
  285. .. code-block:: jinja
  286. {{ '{{' }}
  287. For bigger sections it makes sense to mark a block :doc:`raw<tags/raw>`.
  288. Macros
  289. ------
  290. Macros are comparable with functions in regular programming languages. They
  291. are useful to put often used HTML idioms into reusable elements to not repeat
  292. yourself.
  293. A macro is defined via the :doc:`macro<tags/macro>` tag. Here is a small
  294. example of a macro that renders a form element:
  295. .. code-block:: jinja
  296. {% macro input(name, value, type, size) %}
  297. <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
  298. {% endmacro %}
  299. Macros can be defined in any template, and need to be "imported" before being
  300. used via the :doc:`import<tags/import>` tag:
  301. .. code-block:: jinja
  302. {% import "forms.html" as forms %}
  303. <p>{{ forms.input('username') }}</p>
  304. Alternatively you can import names from the template into the current
  305. namespace via the :doc:`from<tags/from>` tag:
  306. .. code-block:: jinja
  307. {% from 'forms.html' import input as input_field, textarea %}
  308. <dl>
  309. <dt>Username</dt>
  310. <dd>{{ input_field('username') }}</dd>
  311. <dt>Password</dt>
  312. <dd>{{ input_field('password', type='password') }}</dd>
  313. </dl>
  314. <p>{{ textarea('comment') }}</p>
  315. Expressions
  316. -----------
  317. Twig allows expressions everywhere. These work very similar to regular PHP and
  318. even if you're not working with PHP you should feel comfortable with it.
  319. .. note::
  320. The operator precedence is as follows, with the lowest-precedence
  321. operators listed first: ``&``, ``^``, ``|``, ``or``, ``and``, ``==``,
  322. ``!=``, ``<``, ``>``, ``>=``, ``<=``, ``in``, ``..``, ``+``, ``-``, ``~``,
  323. ``*``, ``/``, ``//``, ``%``, ``is``, and ``**``.
  324. Literals
  325. ~~~~~~~~
  326. The simplest form of expressions are literals. Literals are representations
  327. for PHP types such as strings, numbers, and arrays. The following literals
  328. exist:
  329. * ``"Hello World"``: Everything between two double or single quotes is a
  330. string. They are useful whenever you need a string in the template (for
  331. example as arguments to function calls, filters or just to extend or
  332. include a template).
  333. * ``42`` / ``42.23``: Integers and floating point numbers are created by just
  334. writing the number down. If a dot is present the number is a float,
  335. otherwise an integer.
  336. * ``["foo", "bar"]``: Arrays are defined by a sequence of expressions
  337. separated by a comma (``,``) and wrapped with squared brackets (``[]``).
  338. * ``{"foo": "bar"}``: Hashes are defined by a list of keys and values
  339. separated by a comma (``,``) and wrapped with curly braces (``{}``). A value
  340. can be any valid expression.
  341. * ``true`` / ``false``: ``true`` represents the true value, ``false``
  342. represents the false value.
  343. * ``null``: ``null`` represents no specific value. This is the value returned
  344. when a variable does not exist. ``none`` is an alias for ``null``.
  345. Arrays and hashes can be nested:
  346. .. code-block:: jinja
  347. {% set foo = [1, {"foo": "bar"}] %}
  348. Math
  349. ~~~~
  350. Twig allows you to calculate with values. This is rarely useful in templates
  351. but exists for completeness' sake. The following operators are supported:
  352. * ``+``: Adds two objects together (the operands are casted to numbers). ``{{
  353. 1 + 1 }}`` is ``2``.
  354. * ``-``: Substracts the second number from the first one. ``{{ 3 - 2 }}`` is
  355. ``1``.
  356. * ``/``: Divides two numbers. The return value will be a floating point
  357. number. ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``.
  358. * ``%``: Calculates the remainder of an integer division. ``{{ 11 % 7 }}`` is
  359. ``4``.
  360. * ``//``: Divides two numbers and returns the truncated integer result. ``{{
  361. 20 // 7 }}`` is ``2``.
  362. * ``*``: Multiplies the left operand with the right one. ``{{ 2 * 2 }}`` would
  363. return ``4``.
  364. * ``**``: Raises the left operand to the power of the right operand. ``{{ 2**3
  365. }}`` would return ``8``.
  366. Logic
  367. ~~~~~
  368. You can combine multiple expressions with the following operators:
  369. * ``and``: Returns true if the left and the right operands are both true.
  370. * ``or``: Returns true if the left or the right operand is true.
  371. * ``not``: Negates a statement.
  372. * ``(expr)``: Groups an expression.
  373. Comparisons
  374. ~~~~~~~~~~~
  375. The following comparison operators are supported in any expression: ``==``,
  376. ``!=``, ``<``, ``>``, ``>=``, and ``<=``.
  377. Containment Operator
  378. ~~~~~~~~~~~~~~~~~~~~
  379. The ``in`` operator performs containment test.
  380. It returns ``true`` if the left operand is contained in the right:
  381. .. code-block:: jinja
  382. {# returns true #}
  383. {{ 1 in [1, 2, 3] }}
  384. {{ 'cd' in 'abcde' }}
  385. .. tip::
  386. You can use this filter to perform a containment test on strings, arrays,
  387. or objects implementing the ``Traversable`` interface.
  388. To perform a negative test, use the ``not in`` operator:
  389. .. code-block:: jinja
  390. {% if 1 not in [1, 2, 3] %}
  391. {# is equivalent to #}
  392. {% if not (1 in [1, 2, 3]) %}
  393. Test Operator
  394. ~~~~~~~~~~~~~
  395. The ``is`` operator performs tests. Tests can be used to test a variable against
  396. a common expression. The right operand is name of the test:
  397. .. code-block:: jinja
  398. {# find out if a variable is odd #}
  399. {{ name is odd }}
  400. Tests can accept arguments too:
  401. .. code-block:: jinja
  402. {% if loop.index is divisibleby(3) %}
  403. Tests can be negated by using the ``not in`` operator:
  404. .. code-block:: jinja
  405. {% if loop.index is not divisibleby(3) %}
  406. {# is equivalent to #}
  407. {% if not (loop.index is divisibleby(3)) %}
  408. Go to the :doc:`tests<tests/index>` page to learn more about the built-in
  409. tests.
  410. Other Operators
  411. ~~~~~~~~~~~~~~~
  412. The following operators are very useful but don't fit into any of the other
  413. categories:
  414. * ``..``: Creates a sequence based on the operand before and after the
  415. operator (this is just syntactic sugar for the :doc:`range<functions/range>`
  416. function).
  417. * ``|``: Applies a filter.
  418. * ``~``: Converts all operands into strings and concatenates them. ``{{ "Hello
  419. " ~ name ~ "!" }}`` would return (assuming ``name`` is ``'John'``) ``Hello
  420. John!``.
  421. * ``.``, ``[]``: Gets an attribute of an object.
  422. * ``?:``: The PHP ternary operator: ``{{ foo ? 'yes' : 'no' }}``
  423. Whitespace Control
  424. ------------------
  425. .. versionadded:: 1.1
  426. Tag level whitespace control was added in Twig 1.1.
  427. The first newline after a template tag is removed automatically (like in PHP.)
  428. Whitespace is not further modified by the template engine, so each whitespace
  429. (spaces, tabs, newlines etc.) is returned unchanged.
  430. Use the ``spaceless`` tag to remove whitespace *between HTML tags*:
  431. .. code-block:: jinja
  432. {% spaceless %}
  433. <div>
  434. <strong>foo</strong>
  435. </div>
  436. {% endspaceless %}
  437. {# output will be <div><strong>foo</strong></div> #}
  438. In addition to the spaceless tag you can also control whitespace on a per tag
  439. level. By using the whitespace control modifier on your tags, you can trim
  440. leading and or trailing whitespace:
  441. .. code-block:: jinja
  442. {% set value = 'no spaces' %}
  443. {#- No leading/trailing whitespace -#}
  444. {%- if true -%}
  445. {{- value -}}
  446. {%- endif -%}
  447. {# output 'no spaces' #}
  448. The above sample shows the default whitespace control modifier, and how you can
  449. use it to remove whitespace around tags. Trimming space will consume all whitespace
  450. for that side of the tag. It is possible to use whitespace trimming on one side
  451. of a tag:
  452. .. code-block:: jinja
  453. {% set value = 'no spaces' %}
  454. <li> {{- value }} </li>
  455. {# outputs '<li>no spaces </li>' #}
  456. Extensions
  457. ----------
  458. Twig can be easily extended.
  459. If you are looking for new tags, filters, or functions, have a look at the Twig official
  460. `extension repository`_.
  461. If you want to create your own, read :doc:`extensions`.
  462. .. _`Twig bundle`: https://github.com/Anomareh/PHP-Twig.tmbundle
  463. .. _`Jinja syntax plugin`: http://jinja.pocoo.org/2/documentation/integration
  464. .. _`Twig syntax plugin`: https://github.com/blogsh/Twig-netbeans
  465. .. _`Twig plugin`: https://github.com/pulse00/Twig-Eclipse-Plugin
  466. .. _`Twig language definition`: https://github.com/gabrielcorpse/gedit-twig-template-language
  467. .. _`extension repository`: http://github.com/fabpot/Twig-extensions