]>
Commit | Line | Data |
---|---|---|
4f5b44bd NL |
1 | Twig for Template Designers |
2 | =========================== | |
3 | ||
4 | This document describes the syntax and semantics of the template engine and | |
5 | will be most useful as reference to those creating Twig templates. | |
6 | ||
7 | Synopsis | |
8 | -------- | |
9 | ||
10 | A template is simply a text file. It can generate any text-based format (HTML, | |
11 | XML, CSV, LaTeX, etc.). It doesn't have a specific extension, ``.html`` or | |
12 | ``.xml`` are just fine. | |
13 | ||
14 | A template contains **variables** or **expressions**, which get replaced with | |
15 | values when the template is evaluated, and **tags**, which control the logic | |
16 | of the template. | |
17 | ||
18 | Below is a minimal template that illustrates a few basics. We will cover the | |
19 | details later on: | |
20 | ||
21 | .. code-block:: html+jinja | |
22 | ||
23 | <!DOCTYPE html> | |
24 | <html> | |
25 | <head> | |
26 | <title>My Webpage</title> | |
27 | </head> | |
28 | <body> | |
29 | <ul id="navigation"> | |
30 | {% for item in navigation %} | |
31 | <li><a href="{{ item.href }}">{{ item.caption }}</a></li> | |
32 | {% endfor %} | |
33 | </ul> | |
34 | ||
35 | <h1>My Webpage</h1> | |
36 | {{ a_variable }} | |
37 | </body> | |
38 | </html> | |
39 | ||
40 | There are two kinds of delimiters: ``{% ... %}`` and ``{{ ... }}``. The first | |
41 | one is used to execute statements such as for-loops, the latter prints the | |
42 | result of an expression to the template. | |
43 | ||
44 | IDEs Integration | |
45 | ---------------- | |
46 | ||
47 | Many IDEs support syntax highlighting and auto-completion for Twig: | |
48 | ||
49 | * *Textmate* via the `Twig bundle`_ | |
50 | * *Vim* via the `Jinja syntax plugin`_ | |
51 | * *Netbeans* via the `Twig syntax plugin`_ (until 7.1, native as of 7.2) | |
52 | * *PhpStorm* (native as of 2.1) | |
53 | * *Eclipse* via the `Twig plugin`_ | |
54 | * *Sublime Text* via the `Twig bundle`_ | |
55 | * *GtkSourceView* via the `Twig language definition`_ (used by gedit and other projects) | |
56 | * *Coda* and *SubEthaEdit* via the `Twig syntax mode`_ | |
57 | * *Coda 2* via the `other Twig syntax mode`_ | |
58 | * *Komodo* and *Komodo Edit* via the Twig highlight/syntax check mode | |
59 | * *Notepad++* via the `Notepad++ Twig Highlighter`_ | |
60 | * *Emacs* via `web-mode.el`_ | |
61 | ||
62 | Variables | |
63 | --------- | |
64 | ||
65 | The application passes variables to the templates you can mess around in the | |
66 | template. Variables may have attributes or elements on them you can access | |
67 | too. How a variable looks like heavily depends on the application providing | |
68 | those. | |
69 | ||
70 | You can use a dot (``.``) to access attributes of a variable (methods or | |
71 | properties of a PHP object, or items of a PHP array), or the so-called | |
72 | "subscript" syntax (``[]``): | |
73 | ||
74 | .. code-block:: jinja | |
75 | ||
76 | {{ foo.bar }} | |
77 | {{ foo['bar'] }} | |
78 | ||
79 | When the attribute contains special characters (like ``-`` that would be | |
80 | interpreted as the minus operator), use the ``attribute`` function instead to | |
81 | access the variable attribute: | |
82 | ||
83 | .. code-block:: jinja | |
84 | ||
85 | {# equivalent to the non-working foo.data-foo #} | |
86 | {{ attribute(foo, 'data-foo') }} | |
87 | ||
88 | .. note:: | |
89 | ||
90 | It's important to know that the curly braces are *not* part of the | |
91 | variable but the print statement. If you access variables inside tags | |
92 | don't put the braces around. | |
93 | ||
94 | If a variable or attribute does not exist, you will get back a ``null`` value | |
95 | when the ``strict_variables`` option is set to ``false``, otherwise Twig will | |
96 | throw an error (see :ref:`environment options<environment_options>`). | |
97 | ||
98 | .. sidebar:: Implementation | |
99 | ||
100 | For convenience sake ``foo.bar`` does the following things on the PHP | |
101 | layer: | |
102 | ||
103 | * check if ``foo`` is an array and ``bar`` a valid element; | |
104 | * if not, and if ``foo`` is an object, check that ``bar`` is a valid property; | |
105 | * if not, and if ``foo`` is an object, check that ``bar`` is a valid method | |
106 | (even if ``bar`` is the constructor - use ``__construct()`` instead); | |
107 | * if not, and if ``foo`` is an object, check that ``getBar`` is a valid method; | |
108 | * if not, and if ``foo`` is an object, check that ``isBar`` is a valid method; | |
109 | * if not, return a ``null`` value. | |
110 | ||
111 | ``foo['bar']`` on the other hand only works with PHP arrays: | |
112 | ||
113 | * check if ``foo`` is an array and ``bar`` a valid element; | |
114 | * if not, return a ``null`` value. | |
115 | ||
116 | .. note:: | |
117 | ||
118 | If you want to get a dynamic attribute on a variable, use the | |
119 | :doc:`attribute<functions/attribute>` function instead. | |
120 | ||
121 | Global Variables | |
122 | ~~~~~~~~~~~~~~~~ | |
123 | ||
124 | The following variables are always available in templates: | |
125 | ||
126 | * ``_self``: references the current template; | |
127 | * ``_context``: references the current context; | |
128 | * ``_charset``: references the current charset. | |
129 | ||
130 | Setting Variables | |
131 | ~~~~~~~~~~~~~~~~~ | |
132 | ||
133 | You can assign values to variables inside code blocks. Assignments use the | |
134 | :doc:`set<tags/set>` tag: | |
135 | ||
136 | .. code-block:: jinja | |
137 | ||
138 | {% set foo = 'foo' %} | |
139 | {% set foo = [1, 2] %} | |
140 | {% set foo = {'foo': 'bar'} %} | |
141 | ||
142 | Filters | |
143 | ------- | |
144 | ||
145 | Variables can be modified by **filters**. Filters are separated from the | |
146 | variable by a pipe symbol (``|``) and may have optional arguments in | |
147 | parentheses. Multiple filters can be chained. The output of one filter is | |
148 | applied to the next. | |
149 | ||
150 | The following example removes all HTML tags from the ``name`` and title-cases | |
151 | it: | |
152 | ||
153 | .. code-block:: jinja | |
154 | ||
155 | {{ name|striptags|title }} | |
156 | ||
157 | Filters that accept arguments have parentheses around the arguments. This | |
158 | example will join a list by commas: | |
159 | ||
160 | .. code-block:: jinja | |
161 | ||
162 | {{ list|join(', ') }} | |
163 | ||
164 | To apply a filter on a section of code, wrap it with the | |
165 | :doc:`filter<tags/filter>` tag: | |
166 | ||
167 | .. code-block:: jinja | |
168 | ||
169 | {% filter upper %} | |
170 | This text becomes uppercase | |
171 | {% endfilter %} | |
172 | ||
173 | Go to the :doc:`filters<filters/index>` page to learn more about the built-in | |
174 | filters. | |
175 | ||
176 | Functions | |
177 | --------- | |
178 | ||
179 | Functions can be called to generate content. Functions are called by their | |
180 | name followed by parentheses (``()``) and may have arguments. | |
181 | ||
182 | For instance, the ``range`` function returns a list containing an arithmetic | |
183 | progression of integers: | |
184 | ||
185 | .. code-block:: jinja | |
186 | ||
187 | {% for i in range(0, 3) %} | |
188 | {{ i }}, | |
189 | {% endfor %} | |
190 | ||
191 | Go to the :doc:`functions<functions/index>` page to learn more about the | |
192 | built-in functions. | |
193 | ||
194 | Named Arguments | |
195 | --------------- | |
196 | ||
197 | .. versionadded:: 1.12 | |
198 | Support for named arguments was added in Twig 1.12. | |
199 | ||
200 | Arguments for filters and functions can also be passed as *named arguments*: | |
201 | ||
202 | .. code-block:: jinja | |
203 | ||
204 | {% for i in range(low=1, high=10, step=2) %} | |
205 | {{ i }}, | |
206 | {% endfor %} | |
207 | ||
208 | Using named arguments makes your templates more explicit about the meaning of | |
209 | the values you pass as arguments: | |
210 | ||
211 | .. code-block:: jinja | |
212 | ||
213 | {{ data|convert_encoding('UTF-8', 'iso-2022-jp') }} | |
214 | ||
215 | {# versus #} | |
216 | ||
217 | {{ data|convert_encoding(from='iso-2022-jp', to='UTF-8') }} | |
218 | ||
219 | Named arguments also allow you to skip some arguments for which you don't want | |
220 | to change the default value: | |
221 | ||
222 | .. code-block:: jinja | |
223 | ||
224 | {# the first argument is the date format, which defaults to the global date format if null is passed #} | |
225 | {{ "now"|date(null, "Europe/Paris") }} | |
226 | ||
227 | {# or skip the format value by using a named argument for the timezone #} | |
228 | {{ "now"|date(timezone="Europe/Paris") }} | |
229 | ||
230 | You can also use both positional and named arguments in one call, in which | |
231 | case positional arguments must always come before named arguments: | |
232 | ||
233 | .. code-block:: jinja | |
234 | ||
235 | {{ "now"|date('d/m/Y H:i', timezone="Europe/Paris") }} | |
236 | ||
237 | .. tip:: | |
238 | ||
239 | Each function and filter documentation page has a section where the names | |
240 | of all arguments are listed when supported. | |
241 | ||
242 | Control Structure | |
243 | ----------------- | |
244 | ||
245 | A control structure refers to all those things that control the flow of a | |
246 | program - conditionals (i.e. ``if``/``elseif``/``else``), ``for``-loops, as | |
247 | well as things like blocks. Control structures appear inside ``{% ... %}`` | |
248 | blocks. | |
249 | ||
250 | For example, to display a list of users provided in a variable called | |
251 | ``users``, use the :doc:`for<tags/for>` tag: | |
252 | ||
253 | .. code-block:: jinja | |
254 | ||
255 | <h1>Members</h1> | |
256 | <ul> | |
257 | {% for user in users %} | |
258 | <li>{{ user.username|e }}</li> | |
259 | {% endfor %} | |
260 | </ul> | |
261 | ||
262 | The :doc:`if<tags/if>` tag can be used to test an expression: | |
263 | ||
264 | .. code-block:: jinja | |
265 | ||
266 | {% if users|length > 0 %} | |
267 | <ul> | |
268 | {% for user in users %} | |
269 | <li>{{ user.username|e }}</li> | |
270 | {% endfor %} | |
271 | </ul> | |
272 | {% endif %} | |
273 | ||
274 | Go to the :doc:`tags<tags/index>` page to learn more about the built-in tags. | |
275 | ||
276 | Comments | |
277 | -------- | |
278 | ||
279 | To comment-out part of a line in a template, use the comment syntax ``{# ... | |
280 | #}``. This is useful for debugging or to add information for other template | |
281 | designers or yourself: | |
282 | ||
283 | .. code-block:: jinja | |
284 | ||
285 | {# note: disabled template because we no longer use this | |
286 | {% for user in users %} | |
287 | ... | |
288 | {% endfor %} | |
289 | #} | |
290 | ||
291 | Including other Templates | |
292 | ------------------------- | |
293 | ||
294 | The :doc:`include<tags/include>` tag is useful to include a template and | |
295 | return the rendered content of that template into the current one: | |
296 | ||
297 | .. code-block:: jinja | |
298 | ||
299 | {% include 'sidebar.html' %} | |
300 | ||
301 | Per default included templates are passed the current context. | |
302 | ||
303 | The context that is passed to the included template includes variables defined | |
304 | in the template: | |
305 | ||
306 | .. code-block:: jinja | |
307 | ||
308 | {% for box in boxes %} | |
309 | {% include "render_box.html" %} | |
310 | {% endfor %} | |
311 | ||
312 | The included template ``render_box.html`` is able to access ``box``. | |
313 | ||
314 | The filename of the template depends on the template loader. For instance, the | |
315 | ``Twig_Loader_Filesystem`` allows you to access other templates by giving the | |
316 | filename. You can access templates in subdirectories with a slash: | |
317 | ||
318 | .. code-block:: jinja | |
319 | ||
320 | {% include "sections/articles/sidebar.html" %} | |
321 | ||
322 | This behavior depends on the application embedding Twig. | |
323 | ||
324 | Template Inheritance | |
325 | -------------------- | |
326 | ||
327 | The most powerful part of Twig is template inheritance. Template inheritance | |
328 | allows you to build a base "skeleton" template that contains all the common | |
329 | elements of your site and defines **blocks** that child templates can | |
330 | override. | |
331 | ||
332 | Sounds complicated but is very basic. It's easier to understand it by | |
333 | starting with an example. | |
334 | ||
335 | Let's define a base template, ``base.html``, which defines a simple HTML | |
336 | skeleton document that you might use for a simple two-column page: | |
337 | ||
338 | .. code-block:: html+jinja | |
339 | ||
340 | <!DOCTYPE html> | |
341 | <html> | |
342 | <head> | |
343 | {% block head %} | |
344 | <link rel="stylesheet" href="style.css" /> | |
345 | <title>{% block title %}{% endblock %} - My Webpage</title> | |
346 | {% endblock %} | |
347 | </head> | |
348 | <body> | |
349 | <div id="content">{% block content %}{% endblock %}</div> | |
350 | <div id="footer"> | |
351 | {% block footer %} | |
352 | © Copyright 2011 by <a href="http://domain.invalid/">you</a>. | |
353 | {% endblock %} | |
354 | </div> | |
355 | </body> | |
356 | </html> | |
357 | ||
358 | In this example, the :doc:`block<tags/block>` tags define four blocks that | |
359 | child templates can fill in. All the ``block`` tag does is to tell the | |
360 | template engine that a child template may override those portions of the | |
361 | template. | |
362 | ||
363 | A child template might look like this: | |
364 | ||
365 | .. code-block:: jinja | |
366 | ||
367 | {% extends "base.html" %} | |
368 | ||
369 | {% block title %}Index{% endblock %} | |
370 | {% block head %} | |
371 | {{ parent() }} | |
372 | <style type="text/css"> | |
373 | .important { color: #336699; } | |
374 | </style> | |
375 | {% endblock %} | |
376 | {% block content %} | |
377 | <h1>Index</h1> | |
378 | <p class="important"> | |
379 | Welcome to my awesome homepage. | |
380 | </p> | |
381 | {% endblock %} | |
382 | ||
383 | The :doc:`extends<tags/extends>` tag is the key here. It tells the template | |
384 | engine that this template "extends" another template. When the template system | |
385 | evaluates this template, first it locates the parent. The extends tag should | |
386 | be the first tag in the template. | |
387 | ||
388 | Note that since the child template doesn't define the ``footer`` block, the | |
389 | value from the parent template is used instead. | |
390 | ||
391 | It's possible to render the contents of the parent block by using the | |
392 | :doc:`parent<functions/parent>` function. This gives back the results of the | |
393 | parent block: | |
394 | ||
395 | .. code-block:: jinja | |
396 | ||
397 | {% block sidebar %} | |
398 | <h3>Table Of Contents</h3> | |
399 | ... | |
400 | {{ parent() }} | |
401 | {% endblock %} | |
402 | ||
403 | .. tip:: | |
404 | ||
405 | The documentation page for the :doc:`extends<tags/extends>` tag describes | |
406 | more advanced features like block nesting, scope, dynamic inheritance, and | |
407 | conditional inheritance. | |
408 | ||
409 | .. note:: | |
410 | ||
411 | Twig also supports multiple inheritance with the so called horizontal reuse | |
412 | with the help of the :doc:`use<tags/use>` tag. This is an advanced feature | |
413 | hardly ever needed in regular templates. | |
414 | ||
415 | HTML Escaping | |
416 | ------------- | |
417 | ||
418 | When generating HTML from templates, there's always a risk that a variable | |
419 | will include characters that affect the resulting HTML. There are two | |
420 | approaches: manually escaping each variable or automatically escaping | |
421 | everything by default. | |
422 | ||
423 | Twig supports both, automatic escaping is enabled by default. | |
424 | ||
425 | .. note:: | |
426 | ||
427 | Automatic escaping is only supported if the *escaper* extension has been | |
428 | enabled (which is the default). | |
429 | ||
430 | Working with Manual Escaping | |
431 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
432 | ||
433 | If manual escaping is enabled, it is **your** responsibility to escape | |
434 | variables if needed. What to escape? Any variable you don't trust. | |
435 | ||
436 | Escaping works by piping the variable through the | |
437 | :doc:`escape<filters/escape>` or ``e`` filter: | |
438 | ||
439 | .. code-block:: jinja | |
440 | ||
441 | {{ user.username|e }} | |
442 | ||
443 | By default, the ``escape`` filter uses the ``html`` strategy, but depending on | |
444 | the escaping context, you might want to explicitly use any other available | |
445 | strategies: | |
446 | ||
447 | .. code-block:: jinja | |
448 | ||
449 | {{ user.username|e('js') }} | |
450 | {{ user.username|e('css') }} | |
451 | {{ user.username|e('url') }} | |
452 | {{ user.username|e('html_attr') }} | |
453 | ||
454 | Working with Automatic Escaping | |
455 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
456 | ||
457 | Whether automatic escaping is enabled or not, you can mark a section of a | |
458 | template to be escaped or not by using the :doc:`autoescape<tags/autoescape>` | |
459 | tag: | |
460 | ||
461 | .. code-block:: jinja | |
462 | ||
463 | {% autoescape %} | |
464 | Everything will be automatically escaped in this block (using the HTML strategy) | |
465 | {% endautoescape %} | |
466 | ||
467 | By default, auto-escaping uses the ``html`` escaping strategy. If you output | |
468 | variables in other contexts, you need to explicitly escape them with the | |
469 | appropriate escaping strategy: | |
470 | ||
471 | .. code-block:: jinja | |
472 | ||
473 | {% autoescape 'js' %} | |
474 | Everything will be automatically escaped in this block (using the JS strategy) | |
475 | {% endautoescape %} | |
476 | ||
477 | Escaping | |
478 | -------- | |
479 | ||
480 | It is sometimes desirable or even necessary to have Twig ignore parts it would | |
481 | otherwise handle as variables or blocks. For example if the default syntax is | |
482 | used and you want to use ``{{`` as raw string in the template and not start a | |
483 | variable you have to use a trick. | |
484 | ||
485 | The easiest way is to output the variable delimiter (``{{``) by using a variable | |
486 | expression: | |
487 | ||
488 | .. code-block:: jinja | |
489 | ||
490 | {{ '{{' }} | |
491 | ||
492 | For bigger sections it makes sense to mark a block | |
493 | :doc:`verbatim<tags/verbatim>`. | |
494 | ||
495 | Macros | |
496 | ------ | |
497 | ||
498 | .. versionadded:: 1.12 | |
499 | Support for default argument values was added in Twig 1.12. | |
500 | ||
501 | Macros are comparable with functions in regular programming languages. They | |
502 | are useful to reuse often used HTML fragments to not repeat yourself. | |
503 | ||
504 | A macro is defined via the :doc:`macro<tags/macro>` tag. Here is a small example | |
505 | (subsequently called ``forms.html``) of a macro that renders a form element: | |
506 | ||
507 | .. code-block:: jinja | |
508 | ||
509 | {% macro input(name, value, type, size) %} | |
510 | <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" /> | |
511 | {% endmacro %} | |
512 | ||
513 | Macros can be defined in any template, and need to be "imported" via the | |
514 | :doc:`import<tags/import>` tag before being used: | |
515 | ||
516 | .. code-block:: jinja | |
517 | ||
518 | {% import "forms.html" as forms %} | |
519 | ||
520 | <p>{{ forms.input('username') }}</p> | |
521 | ||
522 | Alternatively, you can import individual macro names from a template into the | |
523 | current namespace via the :doc:`from<tags/from>` tag and optionally alias them: | |
524 | ||
525 | .. code-block:: jinja | |
526 | ||
527 | {% from 'forms.html' import input as input_field %} | |
528 | ||
529 | <dl> | |
530 | <dt>Username</dt> | |
531 | <dd>{{ input_field('username') }}</dd> | |
532 | <dt>Password</dt> | |
533 | <dd>{{ input_field('password', '', 'password') }}</dd> | |
534 | </dl> | |
535 | ||
536 | A default value can also be defined for macro arguments when not provided in a | |
537 | macro call: | |
538 | ||
539 | .. code-block:: jinja | |
540 | ||
541 | {% macro input(name, value = "", type = "text", size = 20) %} | |
542 | <input type="{{ type }}" name="{{ name }}" value="{{ value|e }}" size="{{ size }}" /> | |
543 | {% endmacro %} | |
544 | ||
545 | .. _twig-expressions: | |
546 | ||
547 | Expressions | |
548 | ----------- | |
549 | ||
550 | Twig allows expressions everywhere. These work very similar to regular PHP and | |
551 | even if you're not working with PHP you should feel comfortable with it. | |
552 | ||
553 | .. note:: | |
554 | ||
555 | The operator precedence is as follows, with the lowest-precedence | |
556 | operators listed first: ``b-and``, ``b-xor``, ``b-or``, ``or``, ``and``, | |
557 | ``==``, ``!=``, ``<``, ``>``, ``>=``, ``<=``, ``in``, ``..``, ``+``, | |
558 | ``-``, ``~``, ``*``, ``/``, ``//``, ``%``, ``is``, ``**``, ``|``, ``[]``, | |
559 | and ``.``: | |
560 | ||
561 | .. code-block:: jinja | |
562 | ||
563 | {% set greeting = 'Hello' %} | |
564 | {% set name = 'Fabien' %} | |
565 | ||
566 | {{ greeting ~ name|lower }} {# Hello fabien #} | |
567 | ||
568 | {# use parenthesis to change precedence #} | |
569 | {{ (greeting ~ name)|lower }} {# hello fabien #} | |
570 | ||
571 | Literals | |
572 | ~~~~~~~~ | |
573 | ||
574 | .. versionadded:: 1.5 | |
575 | Support for hash keys as names and expressions was added in Twig 1.5. | |
576 | ||
577 | The simplest form of expressions are literals. Literals are representations | |
578 | for PHP types such as strings, numbers, and arrays. The following literals | |
579 | exist: | |
580 | ||
581 | * ``"Hello World"``: Everything between two double or single quotes is a | |
582 | string. They are useful whenever you need a string in the template (for | |
583 | example as arguments to function calls, filters or just to extend or include | |
584 | a template). A string can contain a delimiter if it is preceded by a | |
585 | backslash (``\``) -- like in ``'It\'s good'``. | |
586 | ||
587 | * ``42`` / ``42.23``: Integers and floating point numbers are created by just | |
588 | writing the number down. If a dot is present the number is a float, | |
589 | otherwise an integer. | |
590 | ||
591 | * ``["foo", "bar"]``: Arrays are defined by a sequence of expressions | |
592 | separated by a comma (``,``) and wrapped with squared brackets (``[]``). | |
593 | ||
594 | * ``{"foo": "bar"}``: Hashes are defined by a list of keys and values | |
595 | separated by a comma (``,``) and wrapped with curly braces (``{}``): | |
596 | ||
597 | .. code-block:: jinja | |
598 | ||
599 | {# keys as string #} | |
600 | { 'foo': 'foo', 'bar': 'bar' } | |
601 | ||
602 | {# keys as names (equivalent to the previous hash) -- as of Twig 1.5 #} | |
603 | { foo: 'foo', bar: 'bar' } | |
604 | ||
605 | {# keys as integer #} | |
606 | { 2: 'foo', 4: 'bar' } | |
607 | ||
608 | {# keys as expressions (the expression must be enclosed into parentheses) -- as of Twig 1.5 #} | |
609 | { (1 + 1): 'foo', (a ~ 'b'): 'bar' } | |
610 | ||
611 | * ``true`` / ``false``: ``true`` represents the true value, ``false`` | |
612 | represents the false value. | |
613 | ||
614 | * ``null``: ``null`` represents no specific value. This is the value returned | |
615 | when a variable does not exist. ``none`` is an alias for ``null``. | |
616 | ||
617 | Arrays and hashes can be nested: | |
618 | ||
619 | .. code-block:: jinja | |
620 | ||
621 | {% set foo = [1, {"foo": "bar"}] %} | |
622 | ||
623 | .. tip:: | |
624 | ||
625 | Using double-quoted or single-quoted strings has no impact on performance | |
626 | but string interpolation is only supported in double-quoted strings. | |
627 | ||
628 | Math | |
629 | ~~~~ | |
630 | ||
631 | Twig allows you to calculate with values. This is rarely useful in templates | |
632 | but exists for completeness' sake. The following operators are supported: | |
633 | ||
634 | * ``+``: Adds two objects together (the operands are casted to numbers). ``{{ | |
635 | 1 + 1 }}`` is ``2``. | |
636 | ||
637 | * ``-``: Subtracts the second number from the first one. ``{{ 3 - 2 }}`` is | |
638 | ``1``. | |
639 | ||
640 | * ``/``: Divides two numbers. The returned value will be a floating point | |
641 | number. ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``. | |
642 | ||
643 | * ``%``: Calculates the remainder of an integer division. ``{{ 11 % 7 }}`` is | |
644 | ``4``. | |
645 | ||
646 | * ``//``: Divides two numbers and returns the truncated integer result. ``{{ | |
647 | 20 // 7 }}`` is ``2``. | |
648 | ||
649 | * ``*``: Multiplies the left operand with the right one. ``{{ 2 * 2 }}`` would | |
650 | return ``4``. | |
651 | ||
652 | * ``**``: Raises the left operand to the power of the right operand. ``{{ 2 ** | |
653 | 3 }}`` would return ``8``. | |
654 | ||
655 | Logic | |
656 | ~~~~~ | |
657 | ||
658 | You can combine multiple expressions with the following operators: | |
659 | ||
660 | * ``and``: Returns true if the left and the right operands are both true. | |
661 | ||
662 | * ``or``: Returns true if the left or the right operand is true. | |
663 | ||
664 | * ``not``: Negates a statement. | |
665 | ||
666 | * ``(expr)``: Groups an expression. | |
667 | ||
668 | .. note:: | |
669 | ||
670 | Twig also support bitwise operators (``b-and``, ``b-xor``, and ``b-or``). | |
671 | ||
672 | Comparisons | |
673 | ~~~~~~~~~~~ | |
674 | ||
675 | The following comparison operators are supported in any expression: ``==``, | |
676 | ``!=``, ``<``, ``>``, ``>=``, and ``<=``. | |
677 | ||
678 | Containment Operator | |
679 | ~~~~~~~~~~~~~~~~~~~~ | |
680 | ||
681 | The ``in`` operator performs containment test. | |
682 | ||
683 | It returns ``true`` if the left operand is contained in the right: | |
684 | ||
685 | .. code-block:: jinja | |
686 | ||
687 | {# returns true #} | |
688 | ||
689 | {{ 1 in [1, 2, 3] }} | |
690 | ||
691 | {{ 'cd' in 'abcde' }} | |
692 | ||
693 | .. tip:: | |
694 | ||
695 | You can use this filter to perform a containment test on strings, arrays, | |
696 | or objects implementing the ``Traversable`` interface. | |
697 | ||
698 | To perform a negative test, use the ``not in`` operator: | |
699 | ||
700 | .. code-block:: jinja | |
701 | ||
702 | {% if 1 not in [1, 2, 3] %} | |
703 | ||
704 | {# is equivalent to #} | |
705 | {% if not (1 in [1, 2, 3]) %} | |
706 | ||
707 | Test Operator | |
708 | ~~~~~~~~~~~~~ | |
709 | ||
710 | The ``is`` operator performs tests. Tests can be used to test a variable against | |
711 | a common expression. The right operand is name of the test: | |
712 | ||
713 | .. code-block:: jinja | |
714 | ||
715 | {# find out if a variable is odd #} | |
716 | ||
717 | {{ name is odd }} | |
718 | ||
719 | Tests can accept arguments too: | |
720 | ||
721 | .. code-block:: jinja | |
722 | ||
723 | {% if loop.index is divisibleby(3) %} | |
724 | ||
725 | Tests can be negated by using the ``is not`` operator: | |
726 | ||
727 | .. code-block:: jinja | |
728 | ||
729 | {% if loop.index is not divisibleby(3) %} | |
730 | ||
731 | {# is equivalent to #} | |
732 | {% if not (loop.index is divisibleby(3)) %} | |
733 | ||
734 | Go to the :doc:`tests<tests/index>` page to learn more about the built-in | |
735 | tests. | |
736 | ||
737 | Other Operators | |
738 | ~~~~~~~~~~~~~~~ | |
739 | ||
740 | .. versionadded:: 1.12.0 | |
741 | Support for the extended ternary operator was added in Twig 1.12.0. | |
742 | ||
743 | The following operators are very useful but don't fit into any of the other | |
744 | categories: | |
745 | ||
746 | * ``..``: Creates a sequence based on the operand before and after the | |
747 | operator (this is just syntactic sugar for the :doc:`range<functions/range>` | |
748 | function). | |
749 | ||
750 | * ``|``: Applies a filter. | |
751 | ||
752 | * ``~``: Converts all operands into strings and concatenates them. ``{{ "Hello | |
753 | " ~ name ~ "!" }}`` would return (assuming ``name`` is ``'John'``) ``Hello | |
754 | John!``. | |
755 | ||
756 | * ``.``, ``[]``: Gets an attribute of an object. | |
757 | ||
758 | * ``?:``: The ternary operator: | |
759 | ||
760 | .. code-block:: jinja | |
761 | ||
762 | {{ foo ? 'yes' : 'no' }} | |
763 | ||
764 | {# as of Twig 1.12.0 #} | |
765 | {{ foo ?: 'no' }} == {{ foo ? foo : 'no' }} | |
766 | {{ foo ? 'yes' }} == {{ foo ? 'yes' : '' }} | |
767 | ||
768 | String Interpolation | |
769 | ~~~~~~~~~~~~~~~~~~~~ | |
770 | ||
771 | .. versionadded:: 1.5 | |
772 | String interpolation was added in Twig 1.5. | |
773 | ||
774 | String interpolation (`#{expression}`) allows any valid expression to appear | |
775 | within a *double-quoted string*. The result of evaluating that expression is | |
776 | inserted into the string: | |
777 | ||
778 | .. code-block:: jinja | |
779 | ||
780 | {{ "foo #{bar} baz" }} | |
781 | {{ "foo #{1 + 2} baz" }} | |
782 | ||
783 | Whitespace Control | |
784 | ------------------ | |
785 | ||
786 | .. versionadded:: 1.1 | |
787 | Tag level whitespace control was added in Twig 1.1. | |
788 | ||
789 | The first newline after a template tag is removed automatically (like in PHP.) | |
790 | Whitespace is not further modified by the template engine, so each whitespace | |
791 | (spaces, tabs, newlines etc.) is returned unchanged. | |
792 | ||
793 | Use the ``spaceless`` tag to remove whitespace *between HTML tags*: | |
794 | ||
795 | .. code-block:: jinja | |
796 | ||
797 | {% spaceless %} | |
798 | <div> | |
799 | <strong>foo bar</strong> | |
800 | </div> | |
801 | {% endspaceless %} | |
802 | ||
803 | {# output will be <div><strong>foo bar</strong></div> #} | |
804 | ||
805 | In addition to the spaceless tag you can also control whitespace on a per tag | |
806 | level. By using the whitespace control modifier on your tags, you can trim | |
807 | leading and or trailing whitespace: | |
808 | ||
809 | .. code-block:: jinja | |
810 | ||
811 | {% set value = 'no spaces' %} | |
812 | {#- No leading/trailing whitespace -#} | |
813 | {%- if true -%} | |
814 | {{- value -}} | |
815 | {%- endif -%} | |
816 | ||
817 | {# output 'no spaces' #} | |
818 | ||
819 | The above sample shows the default whitespace control modifier, and how you can | |
820 | use it to remove whitespace around tags. Trimming space will consume all whitespace | |
821 | for that side of the tag. It is possible to use whitespace trimming on one side | |
822 | of a tag: | |
823 | ||
824 | .. code-block:: jinja | |
825 | ||
826 | {% set value = 'no spaces' %} | |
827 | <li> {{- value }} </li> | |
828 | ||
829 | {# outputs '<li>no spaces </li>' #} | |
830 | ||
831 | Extensions | |
832 | ---------- | |
833 | ||
834 | Twig can be easily extended. | |
835 | ||
836 | If you are looking for new tags, filters, or functions, have a look at the Twig official | |
837 | `extension repository`_. | |
838 | ||
839 | If you want to create your own, read the :ref:`Creating an | |
840 | Extension<creating_extensions>` chapter. | |
841 | ||
842 | .. _`Twig bundle`: https://github.com/Anomareh/PHP-Twig.tmbundle | |
843 | .. _`Jinja syntax plugin`: http://jinja.pocoo.org/2/documentation/integration | |
844 | .. _`Twig syntax plugin`: http://plugins.netbeans.org/plugin/37069/php-twig | |
845 | .. _`Twig plugin`: https://github.com/pulse00/Twig-Eclipse-Plugin | |
846 | .. _`Twig language definition`: https://github.com/gabrielcorpse/gedit-twig-template-language | |
847 | .. _`extension repository`: http://github.com/fabpot/Twig-extensions | |
848 | .. _`Twig syntax mode`: https://github.com/bobthecow/Twig-HTML.mode | |
849 | .. _`other Twig syntax mode`: https://github.com/muxx/Twig-HTML.mode | |
850 | .. _`Notepad++ Twig Highlighter`: https://github.com/Banane9/notepadplusplus-twig | |
851 | .. _`web-mode.el`: http://web-mode.org/ |