templates.rst 21KB

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