templates.rst 41KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582
  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 of
  12. the template.
  13. Below is a minimal template that illustrates a few basics. We will cover the
  14. details later in that document:
  15. .. code-block:: jinja
  16. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
  17. <html lang="en">
  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. Variables
  44. ---------
  45. The application passes variables to the templates you can mess around in the
  46. template. Variables may have attributes or elements on them you can access
  47. too. How a variable looks like, heavily depends on the application providing
  48. those.
  49. You can use a dot (``.``) to access attributes of a variable, alternative the
  50. so-called "subscript" syntax (``[]``) can be used. The following lines do the
  51. same:
  52. .. code-block:: jinja
  53. {{ foo.bar }}
  54. {{ foo['bar'] }}
  55. .. note::
  56. It's important to know that the curly braces are *not* part of the
  57. variable but the print statement. If you access variables inside tags
  58. don't put the braces around.
  59. If a variable or attribute does not exist you will get back a ``null`` value
  60. (which can be tested with the ``none`` expression).
  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 works mostly the same with the a small
  72. difference in the order:
  73. * check if ``foo`` is an array and ``bar`` a valid element;
  74. * if not, return a ``null`` value.
  75. Using the alternative syntax is also useful to dynamically get attributes
  76. from arrays:
  77. .. code-block:: jinja
  78. foo[bar]
  79. Twig always references the following variables:
  80. * ``_self``: references the current template;
  81. * ``_context``: references the current context;
  82. * ``_charset``: references the current charset.
  83. Filters
  84. -------
  85. Variables can by modified by **filters**. Filters are separated from the
  86. variable by a pipe symbol (``|``) and may have optional arguments in
  87. parentheses. Multiple filters can be chained. The output of one filter is
  88. applied to the next.
  89. ``{{ name|striptags|title }}`` for example will remove all HTML tags from the
  90. ``name`` and title-cases it. Filters that accept arguments have parentheses
  91. around the arguments, like a function call. This example will join a list by
  92. commas: ``{{ list|join(', ') }}``.
  93. The built-in filters section below describes all the built-in filters.
  94. Comments
  95. --------
  96. To comment-out part of a line in a template, use the comment syntax ``{# ...
  97. #}``. This is useful to comment out parts of the template for debugging or to
  98. add information for other template designers or yourself:
  99. .. code-block:: jinja
  100. {# note: disabled template because we no longer use this
  101. {% for user in users %}
  102. ...
  103. {% endfor %}
  104. #}
  105. Whitespace Control
  106. ------------------
  107. .. versionadded:: 1.1
  108. Tag level whitespace control was added in Twig 1.1.
  109. The first newline after a template tag is removed automatically (like in PHP.)
  110. Whitespace is not further modified by the template engine, so each whitespace
  111. (spaces, tabs, newlines etc.) is returned unchanged.
  112. Use the ``spaceless`` tag to remove whitespace between HTML tags:
  113. .. code-block:: jinja
  114. {% spaceless %}
  115. <div>
  116. <strong>foo</strong>
  117. </div>
  118. {% endspaceless %}
  119. {# output will be <div><strong>foo</strong></div> #}
  120. In addition to the spaceless tag you can also control whitespace on a per tag
  121. level. By using the whitespace control modifier on your tags you can trim
  122. leading and or trailing whitespace from any tag type:
  123. .. code-block:: jinja
  124. {% set value = 'no spaces' %}
  125. {#- No leading/trailing whitespace -#}
  126. {%- if true -%}
  127. {{- value -}}
  128. {%- endif -%}
  129. {# output 'no spaces' #}
  130. The above sample shows the default whitespace control modifier, and how you can
  131. use it to remove whitespace around tags. Trimming space will consume all whitespace
  132. for that side of the tag. It is possible to use whitespace trimming on one side
  133. of a tag:
  134. .. code-block:: jinja
  135. {% set value = 'no spaces' %}
  136. <li> {{- value }} </li>
  137. {# outputs '<li>no spaces </li>' #}
  138. Escaping
  139. --------
  140. It is sometimes desirable or even necessary to have Twig ignore parts it would
  141. otherwise handle as variables or blocks. For example if the default syntax is
  142. used and you want to use ``{{`` as raw string in the template and not start a
  143. variable you have to use a trick.
  144. The easiest way is to output the variable delimiter (``{{``) by using a variable
  145. expression:
  146. .. code-block:: jinja
  147. {{ '{{' }}
  148. For bigger sections it makes sense to mark a block ``raw``. For example to put
  149. Twig syntax as example into a template you can use this snippet:
  150. .. code-block:: jinja
  151. {% raw %}
  152. <ul>
  153. {% for item in seq %}
  154. <li>{{ item }}</li>
  155. {% endfor %}
  156. </ul>
  157. {% endraw %}
  158. Template Inheritance
  159. --------------------
  160. The most powerful part of Twig is template inheritance. Template inheritance
  161. allows you to build a base "skeleton" template that contains all the common
  162. elements of your site and defines **blocks** that child templates can
  163. override.
  164. Sounds complicated but is very basic. It's easiest to understand it by
  165. starting with an example.
  166. Base Template
  167. ~~~~~~~~~~~~~
  168. This template, which we'll call ``base.html``, defines a simple HTML skeleton
  169. document that you might use for a simple two-column page. It's the job of
  170. "child" templates to fill the empty blocks with content:
  171. .. code-block:: jinja
  172. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
  173. <html lang="en">
  174. <head>
  175. {% block head %}
  176. <link rel="stylesheet" href="style.css" />
  177. <title>{% block title %}{% endblock %} - My Webpage</title>
  178. {% endblock %}
  179. </head>
  180. <body>
  181. <div id="content">{% block content %}{% endblock %}</div>
  182. <div id="footer">
  183. {% block footer %}
  184. &copy; Copyright 2009 by <a href="http://domain.invalid/">you</a>.
  185. {% endblock %}
  186. </div>
  187. </body>
  188. </html>
  189. In this example, the ``{% block %}`` tags define four blocks that child
  190. templates can fill in. All the ``block`` tag does is to tell the template
  191. engine that a child template may override those portions of the template.
  192. Child Template
  193. ~~~~~~~~~~~~~~
  194. A child template might look like this:
  195. .. code-block:: jinja
  196. {% extends "base.html" %}
  197. {% block title %}Index{% endblock %}
  198. {% block head %}
  199. {{ parent() }}
  200. <style type="text/css">
  201. .important { color: #336699; }
  202. </style>
  203. {% endblock %}
  204. {% block content %}
  205. <h1>Index</h1>
  206. <p class="important">
  207. Welcome on my awesome homepage.
  208. </p>
  209. {% endblock %}
  210. The ``{% extends %}`` tag is the key here. It tells the template engine that
  211. this template "extends" another template. When the template system evaluates
  212. this template, first it locates the parent. The extends tag should be the
  213. first tag in the template.
  214. The filename of the template depends on the template loader. For example the
  215. ``Twig_Loader_Filesystem`` allows you to access other templates by giving the
  216. filename. You can access templates in subdirectories with a slash:
  217. .. code-block:: jinja
  218. {% extends "layout/default.html" %}
  219. But this behavior can depend on the application embedding Twig. Note that
  220. since the child template doesn't define the ``footer`` block, the value from
  221. the parent template is used instead.
  222. You can't define multiple ``{% block %}`` tags with the same name in the same
  223. template. This limitation exists because a block tag works in "both"
  224. directions. That is, a block tag doesn't just provide a hole to fill - it also
  225. defines the content that fills the hole in the *parent*. If there were two
  226. similarly-named ``{% block %}`` tags in a template, that template's parent
  227. wouldn't know which one of the blocks' content to use. Block names should
  228. consist of alphanumeric characters, and underscores. Dashes are not permitted.
  229. If you want to print a block multiple times you can however use the
  230. ``block`` function:
  231. .. code-block:: jinja
  232. <title>{% block title %}{% endblock %}</title>
  233. <h1>{{ block('title') }}</h1>
  234. {% block body %}{% endblock %}
  235. Like PHP, Twig does not support multiple inheritance. So you can only have one
  236. extends tag called per rendering.
  237. Parent Blocks
  238. ~~~~~~~~~~~~~
  239. It's possible to render the contents of the parent block by using the ``parent``
  240. function. This gives back the results of the parent block:
  241. .. code-block:: jinja
  242. {% block sidebar %}
  243. <h3>Table Of Contents</h3>
  244. ...
  245. {{ parent() }}
  246. {% endblock %}
  247. Named Block End-Tags
  248. ~~~~~~~~~~~~~~~~~~~~
  249. Twig allows you to put the name of the block after the end tag for better
  250. readability:
  251. .. code-block:: jinja
  252. {% block sidebar %}
  253. {% block inner_sidebar %}
  254. ...
  255. {% endblock inner_sidebar %}
  256. {% endblock sidebar %}
  257. However the name after the ``endblock`` word must match the block name.
  258. Block Nesting and Scope
  259. ~~~~~~~~~~~~~~~~~~~~~~~
  260. Blocks can be nested for more complex layouts. Per default, blocks have access
  261. to variables from outer scopes:
  262. .. code-block:: jinja
  263. {% for item in seq %}
  264. <li>{% block loop_item %}{{ item }}{% endblock %}</li>
  265. {% endfor %}
  266. Block Shortcuts
  267. ~~~~~~~~~~~~~~~
  268. For blocks with few content, it's possible to have a shortcut syntax. The
  269. following constructs do the same:
  270. .. code-block:: jinja
  271. {% block title %}
  272. {{ page_title|title }}
  273. {% endblock %}
  274. .. code-block:: jinja
  275. {% block title page_title|title %}
  276. Dynamic Inheritance
  277. ~~~~~~~~~~~~~~~~~~~
  278. Twig supports dynamic inheritance by using a variable as the base template:
  279. .. code-block:: jinja
  280. {% extends some_var %}
  281. If the variable evaluates to a ``Twig_Template`` object, Twig will use it as
  282. the parent template::
  283. // {% extends layout %}
  284. $layout = $twig->loadTemplate('some_layout_template.twig');
  285. $twig->display('template.twig', array('layout' => $layout));
  286. Conditional Inheritance
  287. ~~~~~~~~~~~~~~~~~~~~~~~
  288. As a matter of fact, the template name can be any valid expression. So, it's
  289. also possible to make the inheritance mechanism conditional:
  290. .. code-block:: jinja
  291. {% extends standalone ? "minimum.html" : "base.html" %}
  292. In this example, the template will extend the "minimum.html" layout template
  293. if the ``standalone`` variable evaluates to ``true``, and "base.html"
  294. otherwise.
  295. Import Context Behavior
  296. -----------------------
  297. Per default included templates are passed the current context.
  298. The context that is passed to the included template includes variables defined
  299. in the template:
  300. .. code-block:: jinja
  301. {% for box in boxes %}
  302. {% include "render_box.html" %}
  303. {% endfor %}
  304. The included template ``render_box.html`` is able to access ``box``.
  305. HTML Escaping
  306. -------------
  307. When generating HTML from templates, there's always a risk that a variable
  308. will include characters that affect the resulting HTML. There are two
  309. approaches: manually escaping each variable or automatically escaping
  310. everything by default.
  311. Twig supports both, automatic escaping is enabled by default.
  312. .. note::
  313. Automatic escaping is only supported if the *escaper* extension has been
  314. enabled (which is the default).
  315. Working with Manual Escaping
  316. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  317. If manual escaping is enabled it's **your** responsibility to escape variables
  318. if needed. What to escape? If you have a variable that *may* include any of
  319. the following chars (``>``, ``<``, ``&``, or ``"``) you **have to** escape it unless
  320. the variable contains well-formed and trusted HTML. Escaping works by piping
  321. the variable through the ``|e`` filter: ``{{ user.username|e }}``.
  322. Working with Automatic Escaping
  323. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  324. Whether automatic escaping is enabled or not, you can mark a section of a
  325. template to be escaped or not by using the ``autoescape`` tag:
  326. .. code-block:: jinja
  327. {% autoescape true %}
  328. Everything will be automatically escaped in this block
  329. {% endautoescape %}
  330. {% autoescape false %}
  331. Everything will be outputed as is in this block
  332. {% endautoescape %}
  333. {% autoescape true js %}
  334. Everything will be automatically escaped in this block
  335. using the js escaping strategy
  336. {% endautoescape %}
  337. When automatic escaping is enabled everything is escaped by default except for
  338. values explicitly marked as safe. Those can be marked in the template by using
  339. the ``|raw`` filter.
  340. Functions returning template data (like macros and ``parent``) always return
  341. safe markup.
  342. .. note::
  343. Twig is smart enough to not escape an already escaped value by the
  344. ``escape`` filter.
  345. .. note::
  346. The chapter for developers give more information about when and how
  347. automatic escaping is applied.
  348. List of Control Structures
  349. --------------------------
  350. A control structure refers to all those things that control the flow of a
  351. program - conditionals (i.e. ``if``/``elseif``/``else``), ``for``-loops, as well as
  352. things like blocks. Control structures appear inside ``{% ... %}`` blocks.
  353. For
  354. ~~~
  355. Loop over each item in a sequence. For example, to display a list of users
  356. provided in a variable called ``users``:
  357. .. code-block:: jinja
  358. <h1>Members</h1>
  359. <ul>
  360. {% for user in users %}
  361. <li>{{ user.username|e }}</li>
  362. {% endfor %}
  363. </ul>
  364. .. note::
  365. A sequence can be either an array or an object implementing the
  366. ``Traversable`` interface.
  367. If you do need to iterate over a sequence of numbers, you can use the ``..``
  368. operator:
  369. .. code-block:: jinja
  370. {% for i in 0..10 %}
  371. * {{ i }}
  372. {% endfor %}
  373. The above snippet of code would print all numbers from 0 to 10.
  374. It can be also useful with letters:
  375. .. code-block:: jinja
  376. {% for letter in 'a'..'z' %}
  377. * {{ letter }}
  378. {% endfor %}
  379. The ``..`` operator can take any expression at both sides:
  380. .. code-block:: jinja
  381. {% for letter in 'a'|upper..'z'|upper %}
  382. * {{ letter }}
  383. {% endfor %}
  384. .. tip:
  385. If you need a step different from 1, you can use the ``range`` function
  386. instead.
  387. Inside of a ``for`` loop block you can access some special variables:
  388. ===================== =============================================================
  389. Variable Description
  390. ===================== =============================================================
  391. ``loop.index`` The current iteration of the loop. (1 indexed)
  392. ``loop.index0`` The current iteration of the loop. (0 indexed)
  393. ``loop.revindex`` The number of iterations from the end of the loop (1 indexed)
  394. ``loop.revindex0`` The number of iterations from the end of the loop (0 indexed)
  395. ``loop.first`` True if first iteration
  396. ``loop.last`` True if last iteration
  397. ``loop.length`` The number of items in the sequence
  398. ``loop.parent`` The parent context
  399. ===================== =============================================================
  400. .. note::
  401. The ``loop.length``, ``loop.revindex``, ``loop.revindex0``, and
  402. ``loop.last`` variables are only available for PHP arrays, or objects that
  403. implement the ``Countable`` interface.
  404. .. note::
  405. Unlike in PHP it's not possible to ``break`` or ``continue`` in a loop.
  406. If no iteration took place because the sequence was empty, you can render a
  407. replacement block by using ``else``:
  408. .. code-block:: jinja
  409. <ul>
  410. {% for user in users %}
  411. <li>{{ user.username|e }}</li>
  412. {% else %}
  413. <li><em>no user found</em></li>
  414. {% endfor %}
  415. </ul>
  416. By default, a loop iterates over the values of the sequence. You can iterate
  417. on keys by using the ``keys`` filter:
  418. .. code-block:: jinja
  419. <h1>Members</h1>
  420. <ul>
  421. {% for key in users|keys %}
  422. <li>{{ key }}</li>
  423. {% endfor %}
  424. </ul>
  425. You can also access both keys and values:
  426. .. code-block:: jinja
  427. <h1>Members</h1>
  428. <ul>
  429. {% for key, user in users %}
  430. <li>{{ key }}: {{ user.username|e }}</li>
  431. {% endfor %}
  432. </ul>
  433. If
  434. ~~
  435. The ``if`` statement in Twig is comparable with the if statements of PHP. In
  436. the simplest form you can use it to test if a variable is not empty:
  437. .. code-block:: jinja
  438. {% if users %}
  439. <ul>
  440. {% for user in users %}
  441. <li>{{ user.username|e }}</li>
  442. {% endfor %}
  443. </ul>
  444. {% endif %}
  445. .. note::
  446. If you want to test if the variable is defined, use ``if users is
  447. defined`` instead.
  448. For multiple branches ``elseif`` and ``else`` can be used like in PHP. You can use
  449. more complex ``expressions`` there too:
  450. .. code-block:: jinja
  451. {% if kenny.sick %}
  452. Kenny is sick.
  453. {% elseif kenny.dead %}
  454. You killed Kenny! You bastard!!!
  455. {% else %}
  456. Kenny looks okay --- so far
  457. {% endif %}
  458. Macros
  459. ~~~~~~
  460. Macros are comparable with functions in regular programming languages. They
  461. are useful to put often used HTML idioms into reusable elements to not repeat
  462. yourself.
  463. Here is a small example of a macro that renders a form element:
  464. .. code-block:: jinja
  465. {% macro input(name, value, type, size) %}
  466. <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
  467. {% endmacro %}
  468. Macros differs from native PHP functions in a few ways:
  469. * Default argument values are defined by using the ``default`` filter in the
  470. macro body;
  471. * Arguments of a macro are always optional.
  472. But as PHP functions, macros don't have access to the current template
  473. variables.
  474. .. tip::
  475. You can pass the whole context as an argument by using the special
  476. ``_context`` variable.
  477. Macros can be defined in any template, and need to be "imported" before being
  478. used (see the Import section for more information):
  479. .. code-block:: jinja
  480. {% import "forms.html" as forms %}
  481. The above ``import`` call imports the "forms.html" file (which can contain only
  482. macros, or a template and some macros), and import the functions as items of
  483. the ``forms`` variable.
  484. The macro can then be called at will:
  485. .. code-block:: jinja
  486. <p>{{ forms.input('username') }}</p>
  487. <p>{{ forms.input('password', none, 'password') }}</p>
  488. If macros are defined and used in the same template, you can use the
  489. special ``_self`` variable, without importing them:
  490. .. code-block:: jinja
  491. <p>{{ _self.input('username') }}</p>
  492. When you want to use a macro in another one from the same file, use the ``_self``
  493. variable:
  494. .. code-block:: jinja
  495. {% macro input(name, value, type, size) %}
  496. <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
  497. {% endmacro %}
  498. {% macro wrapped_input(name, value, type, size) %}
  499. <div class="field">
  500. {{ _self.input(name, value, type, size) }}
  501. </div>
  502. {% endmacro %}
  503. When the macro is defined in another file, you need to import it:
  504. .. code-block:: jinja
  505. {# forms.html #}
  506. {% macro input(name, value, type, size) %}
  507. <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
  508. {% endmacro %}
  509. {# shortcuts.html #}
  510. {% macro wrapped_input(name, value, type, size) %}
  511. {% import "forms.html" as forms %}
  512. <div class="field">
  513. {{ forms.input(name, value, type, size) }}
  514. </div>
  515. {% endmacro %}
  516. Filters
  517. ~~~~~~~
  518. Filter sections allow you to apply regular Twig filters on a block of template
  519. data. Just wrap the code in the special ``filter`` section:
  520. .. code-block:: jinja
  521. {% filter upper %}
  522. This text becomes uppercase
  523. {% endfilter %}
  524. You can also chain filters:
  525. .. code-block:: jinja
  526. {% filter lower|escape %}
  527. <strong>SOME TEXT</strong>
  528. {% endfilter %}
  529. It should return ``&lt;strong&gt;some text&lt;/strong&gt;``.
  530. Assignments
  531. ~~~~~~~~~~~
  532. Inside code blocks you can also assign values to variables. Assignments use
  533. the ``set`` tag and can have multiple targets:
  534. .. code-block:: jinja
  535. {% set foo = 'foo' %}
  536. {% set foo = [1, 2] %}
  537. {% set foo = {'foo': 'bar'} %}
  538. {% set foo = 'foo' ~ 'bar' %}
  539. {% set foo, bar = 'foo', 'bar' %}
  540. The ``set`` tag can also be used to 'capture' chunks of text:
  541. .. code-block:: jinja
  542. {% set foo %}
  543. <div id="pagination">
  544. ...
  545. </div>
  546. {% endset %}
  547. .. caution::
  548. If you enable automatic output escaping, Twig will only consider the
  549. content to be safe when capturing chunks of text.
  550. Extends
  551. ~~~~~~~
  552. The ``extends`` tag can be used to extend a template from another one. You can
  553. have multiple of them in a file but only one of them may be executed at the
  554. time. There is no support for multiple inheritance. See the section about
  555. Template inheritance above for more information.
  556. Block
  557. ~~~~~
  558. Blocks are used for inheritance and act as placeholders and replacements at
  559. the same time. They are documented in detail as part of the section about
  560. Template inheritance above.
  561. Include
  562. ~~~~~~~
  563. The ``include`` statement is useful to include a template and return the
  564. rendered content of that file into the current namespace:
  565. .. code-block:: jinja
  566. {% include 'header.html' %}
  567. Body
  568. {% include 'footer.html' %}
  569. Included templates have access to the variables of the active context.
  570. You can add additional variables by passing them after the ``with`` keyword:
  571. .. code-block:: jinja
  572. {# the foo template will have access to the variables from the current context and the foo one #}
  573. {% include 'foo' with {'foo': 'bar'} %}
  574. {% set vars = {'foo': 'bar'} %}
  575. {% include 'foo' with vars %}
  576. You can disable access to the context by appending the ``only`` keyword:
  577. .. code-block:: jinja
  578. {# only the foo variable will be accessible #}
  579. {% include 'foo' with {'foo': 'bar'} only %}
  580. .. code-block:: jinja
  581. {# no variable will be accessible #}
  582. {% include 'foo' only %}
  583. .. tip::
  584. When including a template created by an end user, you should consider
  585. sandboxing it. More information in the "Twig for Developers" chapter.
  586. The template name can be any valid Twig expression:
  587. .. code-block:: jinja
  588. {% include some_var %}
  589. {% include ajax ? 'ajax.html' : 'not_ajax.html' %}
  590. And if the expression evaluates to a ``Twig_Template`` object, Twig will use it
  591. directly::
  592. // {% include template %}
  593. $template = $twig->loadTemplate('some_template.twig');
  594. $twig->loadTemplate('template.twig')->display(array('template' => $template));
  595. Import
  596. ~~~~~~
  597. Twig supports putting often used code into macros. These macros can go into
  598. different templates and get imported from there.
  599. There are two ways to import templates. You can import the complete template
  600. into a variable or request specific macros from it.
  601. Imagine we have a helper module that renders forms (called ``forms.html``):
  602. .. code-block:: jinja
  603. {% macro input(name, value, type, size) %}
  604. <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
  605. {% endmacro %}
  606. {% macro textarea(name, value, rows) %}
  607. <textarea name="{{ name }}" rows="{{ rows|default(10) }}" cols="{{ cols|default(40) }}">{{ value|e }}</textarea>
  608. {% endmacro %}
  609. The easiest and most flexible is importing the whole module into a variable.
  610. That way you can access the attributes:
  611. .. code-block:: jinja
  612. {% import 'forms.html' as forms %}
  613. <dl>
  614. <dt>Username</dt>
  615. <dd>{{ forms.input('username') }}</dd>
  616. <dt>Password</dt>
  617. <dd>{{ forms.input('password', none, 'password') }}</dd>
  618. </dl>
  619. <p>{{ forms.textarea('comment') }}</p>
  620. Alternatively you can import names from the template into the current
  621. namespace:
  622. .. code-block:: jinja
  623. {% from 'forms.html' import input as input_field, textarea %}
  624. <dl>
  625. <dt>Username</dt>
  626. <dd>{{ input_field('username') }}</dd>
  627. <dt>Password</dt>
  628. <dd>{{ input_field('password', type='password') }}</dd>
  629. </dl>
  630. <p>{{ textarea('comment') }}</p>
  631. Importing is not needed if the macros and the template are defined in the same
  632. file; use the special ``_self`` variable instead:
  633. .. code-block:: jinja
  634. {# index.html template #}
  635. {% macro textarea(name, value, rows) %}
  636. <textarea name="{{ name }}" rows="{{ rows|default(10) }}" cols="{{ cols|default(40) }}">{{ value|e }}</textarea>
  637. {% endmacro %}
  638. <p>{{ _self.textarea('comment') }}</p>
  639. But you can still create an alias by importing from the ``_self`` variable:
  640. .. code-block:: jinja
  641. {# index.html template #}
  642. {% macro textarea(name, value, rows) %}
  643. <textarea name="{{ name }}" rows="{{ rows|default(10) }}" cols="{{ cols|default(40) }}">{{ value|e }}</textarea>
  644. {% endmacro %}
  645. {% import _self as forms %}
  646. <p>{{ forms.textarea('comment') }}</p>
  647. Expressions
  648. -----------
  649. Twig allows basic expressions everywhere. These work very similar to regular
  650. PHP and even if you're not working with PHP you should feel comfortable with
  651. it.
  652. The operator precedence is as follows, with the lowest-precedence operators
  653. listed first: ``or``, ``and``, ``==``, ``!=``, ``<``, ``>``, ``>=``, ``<=``, ``in``, ``+``, ``-``,
  654. ``~``, ``*``, ``/``, ``%``, ``//``, ``is``, ``..``, and ``**``.
  655. Literals
  656. ~~~~~~~~
  657. The simplest form of expressions are literals. Literals are representations
  658. for PHP types such as strings, numbers, and arrays. The following literals
  659. exist:
  660. * ``"Hello World"``: Everything between two double or single quotes is a
  661. string. They are useful whenever you need a string in the template (for
  662. example as arguments to function calls, filters or just to extend or
  663. include a template).
  664. * ``42`` / ``42.23``: Integers and floating point numbers are created by just
  665. writing the number down. If a dot is present the number is a float,
  666. otherwise an integer.
  667. * ``["foo", "bar"]``: Arrays are defined by a sequence of expressions
  668. separated by a comma (``,``) and wrapped with squared brackets (``[]``).
  669. * ``{"foo": "bar"}``: Hashes are defined by a list of keys and values
  670. separated by a comma (``,``) and wrapped with curly braces (``{}``). A value
  671. can be any valid expression.
  672. * ``true`` / ``false``: ``true`` represents the true value, ``false``
  673. represents the false value.
  674. * ``none``: ``none`` represents no specific value (the equivalent of ``null`` in
  675. PHP). This is the value returned when a variable does not exist.
  676. Arrays and hashes can be nested:
  677. .. code-block:: jinja
  678. {% set foo = [1, {"foo": "bar"}] %}
  679. Math
  680. ~~~~
  681. Twig allows you to calculate with values. This is rarely useful in templates
  682. but exists for completeness' sake. The following operators are supported:
  683. * ``+``: Adds two objects together (the operands are casted to numbers). ``{{
  684. 1 + 1 }}`` is ``2``.
  685. * ``-``: Substracts the second number from the first one. ``{{ 3 - 2 }}`` is
  686. ``1``.
  687. * ``/``: Divides two numbers. The return value will be a floating point
  688. number. ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``.
  689. * ``%``: Calculates the remainder of an integer division. ``{{ 11 % 7 }}`` is
  690. ``4``.
  691. * ``//``: Divides two numbers and returns the truncated integer result. ``{{
  692. 20 // 7 }}`` is ``2``.
  693. * ``*``: Multiplies the left operand with the right one. ``{{ 2 * 2 }}`` would
  694. return ``4``.
  695. * ``**``: Raises the left operand to the power of the right operand. ``{{ 2**3
  696. }}`` would return ``8``.
  697. Logic
  698. ~~~~~
  699. For ``if`` statements, ``for`` filtering or ``if`` expressions it can be useful to
  700. combine multiple expressions:
  701. * ``and``: Returns true if the left and the right operands are both true.
  702. * ``or``: Returns true if the left or the right operand is true.
  703. * ``not``: Negates a statement.
  704. * ``(expr)``: Groups an expression.
  705. Comparisons
  706. ~~~~~~~~~~~
  707. The following comparison operators are supported in any expression: ``==``,
  708. ``!=``, ``<``, ``>``, ``>=``, and ``<=``.
  709. Containment Operator
  710. ~~~~~~~~~~~~~~~~~~~~
  711. The ``in`` operator performs containment test.
  712. It returns ``true`` if the left operand is contained in the right:
  713. .. code-block:: jinja
  714. {# returns true #}
  715. {{ 1 in [1, 2, 3] }}
  716. {{ 'cd' in 'abcde' }}
  717. .. tip::
  718. You can use this filter to perform a containment test on strings, arrays,
  719. or objects implementing the ``Traversable`` interface.
  720. To perform a negative test, use the ``not in`` operator:
  721. .. code-block:: jinja
  722. {% if 1 not in [1, 2, 3] %}
  723. {# is equivalent to #}
  724. {% if not (1 in [1, 2, 3]) %}
  725. Tests
  726. ~~~~~
  727. The ``is`` operator performs tests. Tests can be used to test a variable against
  728. a common expression. The right operand is name of the test:
  729. .. code-block:: jinja
  730. {# find out if a variable is odd #}
  731. {{ name is odd }}
  732. Tests can accept arguments too:
  733. .. code-block:: jinja
  734. {% if loop.index is divisibleby(3) %}
  735. Tests can be negated by using the ``not in`` operator:
  736. .. code-block:: jinja
  737. {% if loop.index is not divisibleby(3) %}
  738. {# is equivalent to #}
  739. {% if not (loop.index is divisibleby(3)) %}
  740. The built-in tests section below describes all the built-in tests.
  741. Other Operators
  742. ~~~~~~~~~~~~~~~
  743. The following operators are very useful but don't fit into any of the other
  744. two categories:
  745. * ``..``: Creates a sequence based on the operand before and after the
  746. operator (see the ``for`` tag for some usage examples).
  747. * ``|``: Applies a filter.
  748. * ``~``: Converts all operands into strings and concatenates them. ``{{ "Hello
  749. " ~ name ~ "!" }}`` would return (assuming ``name`` is ``'John'``) ``Hello
  750. John!``.
  751. * ``.``, ``[]``: Gets an attribute of an object.
  752. * ``?:``: Twig supports the PHP ternary operator:
  753. .. code-block:: jinja
  754. {{ foo ? 'yes' : 'no' }}
  755. List of built-in Filters
  756. ------------------------
  757. ``date``
  758. ~~~~~~~~
  759. .. versionadded:: 1.1
  760. The timezone support has been added in Twig 1.1.
  761. The ``date`` filter is able to format a date to a given format:
  762. .. code-block:: jinja
  763. {{ post.published_at|date("m/d/Y") }}
  764. The ``date`` filter accepts any date format supported by `DateTime`_ and
  765. ``DateTime`` instances. For instance, to display the current date, filter the
  766. word "now":
  767. .. code-block:: jinja
  768. {{ "now"|date("m/d/Y") }}
  769. To escape words and characters in the date format use ``\\`` in front of each character:
  770. .. code-block:: jinja
  771. {{ post.published_at|date("F jS \\a\\t g:ia") }}
  772. You can also specify a timezone:
  773. {{ post.published_at|date("m/d/Y", "Europe/Paris") }}
  774. ``format``
  775. ~~~~~~~~~~
  776. The ``format`` filter formats a given string by replacing the placeholders
  777. (placeholders follows the ``printf`` notation):
  778. .. code-block:: jinja
  779. {{ "I like %s and %s."|format(foo, "bar") }}
  780. {# returns I like foo and bar. (if the foo parameter equals to the foo string) #}
  781. ``replace``
  782. ~~~~~~~~~~~
  783. The ``replace`` filter formats a given string by replacing the placeholders
  784. (placeholders are free-form):
  785. .. code-block:: jinja
  786. {{ "I like %this% and %that%."|replace({'%this%': foo, '%that%': "bar"}) }}
  787. {# returns I like foo and bar. (if the foo parameter equals to the foo string) #}
  788. ``url_encode``
  789. ~~~~~~~~~~~~~~
  790. The ``url_encode`` filter URL encodes a given string.
  791. ``json_encode``
  792. ~~~~~~~~~~~~~~~
  793. The ``json_encode`` filter returns the JSON representation of a string.
  794. ``title``
  795. ~~~~~~~~~
  796. The ``title`` filter returns a titlecased version of the value. I.e. words will
  797. start with uppercase letters, all remaining characters are lowercase.
  798. ``capitalize``
  799. ~~~~~~~~~~~~~~
  800. The ``capitalize`` filter capitalizes a value. The first character will be
  801. uppercase, all others lowercase.
  802. ``upper``
  803. ~~~~~~~~~
  804. The ``upper`` filter converts a value to uppercase.
  805. ``lower``
  806. ~~~~~~~~~
  807. The ``lower`` filter converts a value to lowercase.
  808. ``striptags``
  809. ~~~~~~~~~~~~~
  810. The ``striptags`` filter strips SGML/XML tags and replace adjacent whitespace by
  811. one space.
  812. ``join``
  813. ~~~~~~~~
  814. The ``join`` filter returns a string which is the concatenation of the strings
  815. in the sequence. The separator between elements is an empty string per
  816. default, you can define it with the optional parameter:
  817. .. code-block:: jinja
  818. {{ [1, 2, 3]|join('|') }}
  819. {# returns 1|2|3 #}
  820. {{ [1, 2, 3]|join }}
  821. {# returns 123 #}
  822. ``reverse``
  823. ~~~~~~~~~~~
  824. The ``reverse`` filter reverses an array or an object if it implements the
  825. ``Iterator`` interface.
  826. ``length``
  827. ~~~~~~~~~~
  828. The ``length`` filters returns the number of items of a sequence or mapping, or
  829. the length of a string.
  830. ``sort``
  831. ~~~~~~~~
  832. The ``sort`` filter sorts an array.
  833. ``default``
  834. ~~~~~~~~~~~
  835. The ``default`` filter returns the passed default value if the value is
  836. undefined or empty, otherwise the value of the variable:
  837. .. code-block:: jinja
  838. {{ var|default('var is not defined') }}
  839. {{ var.foo|default('foo item on var is not defined') }}
  840. {{ ''|default('passed var is empty') }}
  841. .. note::
  842. Read the documentation for the ``defined`` and ``empty`` tests below to
  843. learn more about their semantics.
  844. ``keys``
  845. ~~~~~~~~
  846. The ``keys`` filter returns the keys of an array. It is useful when you want to
  847. iterate over the keys of an array:
  848. .. code-block:: jinja
  849. {% for key in array|keys %}
  850. ...
  851. {% endfor %}
  852. ``escape``, ``e``
  853. ~~~~~~~~~~~~~~~~~
  854. The ``escape`` filter converts the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in
  855. strings to HTML-safe sequences. Use this if you need to display text that
  856. might contain such characters in HTML.
  857. .. note::
  858. Internally, ``escape`` uses the PHP ``htmlspecialchars`` function.
  859. ``raw``
  860. ~~~~~~~
  861. The ``raw`` filter marks the value as safe which means that in an environment
  862. with automatic escaping enabled this variable will not be escaped if ``raw`` is
  863. the last filter applied to it.
  864. .. code-block:: jinja
  865. {% autoescape true %}
  866. {{ var|raw }} {# var won't be escaped #}
  867. {% endautoescape %}
  868. ``merge``
  869. ~~~~~~~~~
  870. The ``merge`` filter merges an array or a hash with the value:
  871. .. code-block:: jinja
  872. {% set items = { 'apple': 'fruit', 'orange': 'fruit' } %}
  873. {% set items = items|merge({ 'peugeot': 'car' }) %}
  874. {# items now contains { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'car' } #}
  875. List of built-in Tests
  876. ----------------------
  877. ``divisibleby``
  878. ~~~~~~~~~~~~~~~
  879. ``divisibleby`` checks if a variable is divisible by a number:
  880. .. code-block:: jinja
  881. {% if loop.index is divisibleby(3) %}
  882. ``none``
  883. ~~~~~~~~
  884. ``none`` returns ``true`` if the variable is ``none``:
  885. .. code-block:: jinja
  886. {{ var is none }}
  887. ``even``
  888. ~~~~~~~~
  889. ``even`` returns ``true`` if the given number is even:
  890. .. code-block:: jinja
  891. {{ var is even }}
  892. ``odd``
  893. ~~~~~~~
  894. ``odd`` returns ``true`` if the given number is odd:
  895. .. code-block:: jinja
  896. {{ var is odd }}
  897. ``sameas``
  898. ~~~~~~~~~~
  899. ``sameas`` checks if a variable points to the same memory address than another
  900. variable:
  901. .. code-block:: jinja
  902. {% if foo.attribute is sameas(false) %}
  903. the foo attribute really is the ``false`` PHP value
  904. {% endif %}
  905. ``constant``
  906. ~~~~~~~~~~~~
  907. ``constant`` checks if a variable has the exact same value as a constant. You
  908. can use either global constants or class constants:
  909. .. code-block:: jinja
  910. {% if post.status is constant('Post::PUBLISHED') %}
  911. the status attribute is exactly the same as Post::PUBLISHED
  912. {% endif %}
  913. ``defined``
  914. ~~~~~~~~~~~
  915. ``defined`` checks if a variable is defined in the current context. This is very
  916. useful if you use the ``strict_variables`` option:
  917. .. code-block:: jinja
  918. {# defined works with variable names #}
  919. {% if foo is defined %}
  920. ...
  921. {% endif %}
  922. {# and attributes on variables names #}
  923. {% if foo.bar is defined %}
  924. ...
  925. {% endif %}
  926. ``empty``
  927. ~~~~~~~~~
  928. ``empty`` checks if a variable is empty:
  929. .. code-block:: jinja
  930. {# evaluates to true if the foo variable is null, false, or the empty string #}
  931. {% if foo is empty %}
  932. ...
  933. {% endif %}
  934. List of Global Functions
  935. ------------------------
  936. The following functions are available in the global scope by default:
  937. ``range``
  938. ~~~~~~~~~
  939. Returns a list containing an arithmetic progression of integers. When step is
  940. given, it specifies the increment (or decrement):
  941. .. code-block:: jinja
  942. {% for i in range(0, 3) %}
  943. {{ i }},
  944. {% endfor %}
  945. {# returns 0, 1, 2, 3 #}
  946. {% for i in range(0, 6, 2) %}
  947. {{ i }},
  948. {% endfor %}
  949. {# returns 0, 2, 4, 6 #}
  950. .. tip::
  951. The ``range`` function works as the native PHP ``range`` function.
  952. The ``..`` operator is a syntactic sugar for the ``range`` function (with a
  953. step of 1):
  954. .. code-block:: jinja
  955. {% for i in 0..10 %}
  956. {{ i }},
  957. {% endfor %}
  958. ``cycle``
  959. ~~~~~~~~~
  960. The ``cycle`` function can be used to cycle on an array of values:
  961. .. code-block:: jinja
  962. {% for i in 0..10 %}
  963. {{ cycle(['odd', 'even'], i) }}
  964. {% endfor %}
  965. The array can contain any number of values:
  966. .. code-block:: jinja
  967. {% set fruits = ['apple', 'orange', 'citrus'] %}
  968. {% for i in 0..10 %}
  969. {{ cycle(fruits, i) }}
  970. {% endfor %}
  971. ``constant``
  972. ~~~~~~~~~~~~
  973. ``constant`` returns the constant value for a given string:
  974. .. code-block:: jinja
  975. {{ some_date|date(constant('DATE_W3C')) }}
  976. Extensions
  977. ----------
  978. Twig can be easily extended. If you are looking for new tags or filters, have
  979. a look at the Twig official extension repository:
  980. http://github.com/fabpot/Twig-extensions.
  981. Horizontal Reuse
  982. ----------------
  983. .. versionadded:: 1.1
  984. Horizontal reuse was added in Twig 1.1.
  985. .. note::
  986. Horizontal reuse is an advanced Twig feature that is hardly ever needed in
  987. regular templates. It is mainly used by projects that need to make
  988. template blocks reusable without using inheritance.
  989. Template inheritance is one of the most powerful Twig's feature but it is
  990. limited to single inheritance; a template can only extend one other template.
  991. This limitation makes template inheritance simple to understand and easy to
  992. debug:
  993. .. code-block:: jinja
  994. {% extends "base.html" %}
  995. {% block title %}{% endblock %}
  996. {% block content %}{% endblock %}
  997. Horizontal reuse is a way to achieve the same goal as multiple inheritance,
  998. but without the associated complexity:
  999. .. code-block:: jinja
  1000. {% extends "base.html" %}
  1001. {% use "blocks.html" %}
  1002. {% block title %}{% endblock %}
  1003. {% block content %}{% endblock %}
  1004. The ``use`` statement tells Twig to import the blocks defined in
  1005. ```blocks.html`` into the current template (it's like macros, but for blocks):
  1006. .. code-block:: jinja
  1007. # blocks.html
  1008. {% block sidebar %}{% endblock %}
  1009. In this example, the ``use`` statement imports the ``sidebar`` block into the
  1010. main template. The code is mostly equivalent to the following one (the
  1011. imported blocks are not outputted automatically):
  1012. .. code-block:: jinja
  1013. {% extends "base.html" %}
  1014. {% block sidebar %}{% endblock %}
  1015. {% block title %}{% endblock %}
  1016. {% block content %}{% endblock %}
  1017. .. note::
  1018. The ``use`` tag only imports a template if it does not extend another
  1019. template, if it does not define macros, and if the body is empty. But it
  1020. can *use* other templates.
  1021. .. note::
  1022. Because ``use`` statements are resolved independently of the context
  1023. passed to the template, the template reference cannot be an expression.
  1024. The main template can also override any imported block. If the template
  1025. already defines the ``sidebar`` block, then the one defined in ``blocks.html``
  1026. is ignored. To avoid name conflicts, you can rename imported blocks:
  1027. .. code-block:: jinja
  1028. {% extends "base.html" %}
  1029. {% use "blocks.html" with sidebar as base_sidebar %}
  1030. {% block sidebar %}{% endblock %}
  1031. {% block title %}{% endblock %}
  1032. {% block content %}{% endblock %}
  1033. Renaming also allows you to simulate inheritance by calling the "parent" block
  1034. (like what you would have done with ``parent()``):
  1035. .. code-block:: jinja
  1036. {% extends "base.html" %}
  1037. {% use "blocks.html" with sidebar as parent_sidebar %}
  1038. {% block sidebar %}
  1039. {{ block('parent_sidebar') }}
  1040. {% endblock %}
  1041. {% block title %}{% endblock %}
  1042. {% block content %}{% endblock %}
  1043. .. note::
  1044. You can use as many ``use`` statements as you want in any given template.
  1045. If two imported templates define the same block, the latest one wins.
  1046. .. _`Twig bundle`: https://github.com/Anomareh/PHP-Twig.tmbundle
  1047. .. _`Jinja syntax plugin`: http://jinja.pocoo.org/2/documentation/integration
  1048. .. _`Twig syntax plugin`: https://github.com/blogsh/Twig-netbeans
  1049. .. _`Twig plugin`: https://github.com/pulse00/Twig-Eclipse-Plugin
  1050. .. _`DateTime`: http://www.php.net/manual/en/datetime.construct.php