templates.rst 21KB

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