1Twig for Developers 2=================== 3 4This chapter describes the API to Twig and not the template language. It will 5be most useful as reference to those implementing the template interface to 6the application and not those who are creating Twig templates. 7 8Basics 9------ 10 11Twig uses a central object called the **environment** (of class 12``\Twig\Environment``). Instances of this class are used to store the 13configuration and extensions, and are used to load templates from the file 14system or other locations. 15 16Most applications will create one ``\Twig\Environment`` object on application 17initialization and use that to load templates. In some cases it's however 18useful to have multiple environments side by side, if different configurations 19are in use. 20 21The simplest way to configure Twig to load templates for your application 22looks roughly like this:: 23 24 require_once '/path/to/lib/Twig/Autoloader.php'; 25 Twig_Autoloader::register(); 26 27 $loader = new \Twig\Loader\FilesystemLoader('/path/to/templates'); 28 $twig = new \Twig\Environment($loader, [ 29 'cache' => '/path/to/compilation_cache', 30 ]); 31 32This will create a template environment with the default settings and a loader 33that looks up the templates in the ``/path/to/templates/`` folder. Different 34loaders are available and you can also write your own if you want to load 35templates from a database or other resources. 36 37.. note:: 38 39 Notice that the second argument of the environment is an array of options. 40 The ``cache`` option is a compilation cache directory, where Twig caches 41 the compiled templates to avoid the parsing phase for sub-sequent 42 requests. It is very different from the cache you might want to add for 43 the evaluated templates. For such a need, you can use any available PHP 44 cache library. 45 46Rendering Templates 47------------------- 48 49To load a template from a Twig environment, call the ``load()`` method which 50returns a ``\Twig\TemplateWrapper`` instance:: 51 52 $template = $twig->load('index.html'); 53 54.. note:: 55 56 Before Twig 1.28, you should use ``loadTemplate()`` instead which returns a 57 ``\Twig\Template`` instance. 58 59To render the template with some variables, call the ``render()`` method:: 60 61 echo $template->render(['the' => 'variables', 'go' => 'here']); 62 63.. note:: 64 65 The ``display()`` method is a shortcut to output the template directly. 66 67You can also load and render the template in one fell swoop:: 68 69 echo $twig->render('index.html', ['the' => 'variables', 'go' => 'here']); 70 71.. versionadded:: 1.28 72 The possibility to render blocks from the API was added in Twig 1.28. 73 74If a template defines blocks, they can be rendered individually via the 75``renderBlock()`` call:: 76 77 echo $template->renderBlock('block_name', ['the' => 'variables', 'go' => 'here']); 78 79.. _environment_options: 80 81Environment Options 82------------------- 83 84When creating a new ``\Twig\Environment`` instance, you can pass an array of 85options as the constructor second argument:: 86 87 $twig = new \Twig\Environment($loader, ['debug' => true]); 88 89The following options are available: 90 91* ``debug`` *boolean* 92 93 When set to ``true``, the generated templates have a 94 ``__toString()`` method that you can use to display the generated nodes 95 (default to ``false``). 96 97* ``charset`` *string* (defaults to ``utf-8``) 98 99 The charset used by the templates. 100 101* ``base_template_class`` *string* (defaults to ``\Twig\Template``) 102 103 The base template class to use for generated 104 templates. 105 106* ``cache`` *string* or ``false`` 107 108 An absolute path where to store the compiled templates, or 109 ``false`` to disable caching (which is the default). 110 111* ``auto_reload`` *boolean* 112 113 When developing with Twig, it's useful to recompile the 114 template whenever the source code changes. If you don't provide a value for 115 the ``auto_reload`` option, it will be determined automatically based on the 116 ``debug`` value. 117 118* ``strict_variables`` *boolean* 119 120 If set to ``false``, Twig will silently ignore invalid 121 variables (variables and or attributes/methods that do not exist) and 122 replace them with a ``null`` value. When set to ``true``, Twig throws an 123 exception instead (default to ``false``). 124 125* ``autoescape`` *string* or *boolean* 126 127 If set to ``true``, HTML auto-escaping will be enabled by 128 default for all templates (default to ``true``). 129 130 As of Twig 1.8, you can set the escaping strategy to use (``html``, ``js``, 131 ``false`` to disable). 132 133 As of Twig 1.9, you can set the escaping strategy to use (``css``, ``url``, 134 ``html_attr``, or a PHP callback that takes the template name and must 135 return the escaping strategy to use -- the callback cannot be a function name 136 to avoid collision with built-in escaping strategies). 137 138 As of Twig 1.17, the ``filename`` escaping strategy (renamed to ``name`` as 139 of Twig 1.27) determines the escaping strategy to use for a template based on 140 the template filename extension (this strategy does not incur any overhead at 141 runtime as auto-escaping is done at compilation time.) 142 143* ``optimizations`` *integer* 144 145 A flag that indicates which optimizations to apply 146 (default to ``-1`` -- all optimizations are enabled; set it to ``0`` to 147 disable). 148 149Loaders 150------- 151 152Loaders are responsible for loading templates from a resource such as the file 153system. 154 155Compilation Cache 156~~~~~~~~~~~~~~~~~ 157 158All template loaders can cache the compiled templates on the filesystem for 159future reuse. It speeds up Twig a lot as templates are only compiled once; and 160the performance boost is even larger if you use a PHP accelerator such as APC. 161See the ``cache`` and ``auto_reload`` options of ``\Twig\Environment`` above 162for more information. 163 164Built-in Loaders 165~~~~~~~~~~~~~~~~ 166 167Here is a list of the built-in loaders Twig provides: 168 169``\Twig\Loader\FilesystemLoader`` 170................................. 171 172.. versionadded:: 1.10 173 The ``prependPath()`` and support for namespaces were added in Twig 1.10. 174 175.. versionadded:: 1.27 176 Relative paths support was added in Twig 1.27. 177 178``\Twig\Loader\FilesystemLoader`` loads templates from the file system. This loader 179can find templates in folders on the file system and is the preferred way to 180load them:: 181 182 $loader = new \Twig\Loader\FilesystemLoader($templateDir); 183 184It can also look for templates in an array of directories:: 185 186 $loader = new \Twig\Loader\FilesystemLoader([$templateDir1, $templateDir2]); 187 188With such a configuration, Twig will first look for templates in 189``$templateDir1`` and if they do not exist, it will fallback to look for them 190in the ``$templateDir2``. 191 192You can add or prepend paths via the ``addPath()`` and ``prependPath()`` 193methods:: 194 195 $loader->addPath($templateDir3); 196 $loader->prependPath($templateDir4); 197 198The filesystem loader also supports namespaced templates. This allows to group 199your templates under different namespaces which have their own template paths. 200 201When using the ``setPaths()``, ``addPath()``, and ``prependPath()`` methods, 202specify the namespace as the second argument (when not specified, these 203methods act on the "main" namespace):: 204 205 $loader->addPath($templateDir, 'admin'); 206 207Namespaced templates can be accessed via the special 208``@namespace_name/template_path`` notation:: 209 210 $twig->render('@admin/index.html', []); 211 212``\Twig\Loader\FilesystemLoader`` support absolute and relative paths. Using relative 213paths is preferred as it makes the cache keys independent of the project root 214directory (for instance, it allows warming the cache from a build server where 215the directory might be different from the one used on production servers):: 216 217 $loader = new \Twig\Loader\FilesystemLoader('templates', getcwd().'/..'); 218 219.. note:: 220 221 When not passing the root path as a second argument, Twig uses ``getcwd()`` 222 for relative paths. 223 224``\Twig\Loader\ArrayLoader`` 225............................ 226 227``\Twig\Loader\ArrayLoader`` loads a template from a PHP array. It's passed an array 228of strings bound to template names:: 229 230 $loader = new \Twig\Loader\ArrayLoader([ 231 'index.html' => 'Hello {{ name }}!', 232 ]); 233 $twig = new \Twig\Environment($loader); 234 235 echo $twig->render('index.html', ['name' => 'Fabien']); 236 237This loader is very useful for unit testing. It can also be used for small 238projects where storing all templates in a single PHP file might make sense. 239 240.. tip:: 241 242 When using the ``Array`` or ``String`` loaders with a cache mechanism, you 243 should know that a new cache key is generated each time a template content 244 "changes" (the cache key being the source code of the template). If you 245 don't want to see your cache grows out of control, you need to take care 246 of clearing the old cache file by yourself. 247 248``\Twig\Loader\ChainLoader`` 249............................ 250 251``\Twig\Loader\ChainLoader`` delegates the loading of templates to other loaders:: 252 253 $loader1 = new \Twig\Loader\ArrayLoader([ 254 'base.html' => '{% block content %}{% endblock %}', 255 ]); 256 $loader2 = new \Twig\Loader\ArrayLoader([ 257 'index.html' => '{% extends "base.html" %}{% block content %}Hello {{ name }}{% endblock %}', 258 'base.html' => 'Will never be loaded', 259 ]); 260 261 $loader = new \Twig\Loader\ChainLoader([$loader1, $loader2]); 262 263 $twig = new \Twig\Environment($loader); 264 265When looking for a template, Twig will try each loader in turn and it will 266return as soon as the template is found. When rendering the ``index.html`` 267template from the above example, Twig will load it with ``$loader2`` but the 268``base.html`` template will be loaded from ``$loader1``. 269 270``\Twig\Loader\ChainLoader`` accepts any loader that implements 271``\Twig\Loader\LoaderInterface``. 272 273.. note:: 274 275 You can also add loaders via the ``addLoader()`` method. 276 277Create your own Loader 278~~~~~~~~~~~~~~~~~~~~~~ 279 280All loaders implement the ``\Twig\Loader\LoaderInterface``:: 281 282 interface Twig_LoaderInterface 283 { 284 /** 285 * Gets the source code of a template, given its name. 286 * 287 * @param string $name string The name of the template to load 288 * 289 * @return string The template source code 290 * 291 * @deprecated since 1.27 (to be removed in 2.0), implement \Twig\Loader\SourceContextLoaderInterface 292 */ 293 function getSource($name); 294 295 /** 296 * Gets the cache key to use for the cache for a given template name. 297 * 298 * @param string $name string The name of the template to load 299 * 300 * @return string The cache key 301 */ 302 function getCacheKey($name); 303 304 /** 305 * Returns true if the template is still fresh. 306 * 307 * @param string $name The template name 308 * @param timestamp $time The last modification time of the cached template 309 */ 310 function isFresh($name, $time); 311 } 312 313The ``isFresh()`` method must return ``true`` if the current cached template 314is still fresh, given the last modification time, or ``false`` otherwise. 315 316.. note:: 317 318 As of Twig 1.27, you should also implement 319 ``\Twig\Loader\SourceContextLoaderInterface`` to avoid deprecation notices. 320 321.. tip:: 322 323 As of Twig 1.11.0, you can also implement ``\Twig\Loader\ExistsLoaderInterface`` 324 to make your loader faster when used with the chain loader. 325 326Using Extensions 327---------------- 328 329Twig extensions are packages that add new features to Twig. Using an 330extension is as simple as using the ``addExtension()`` method:: 331 332 $twig->addExtension(new \Twig\Extension\SandboxExtension()); 333 334Twig comes bundled with the following extensions: 335 336* *Twig_Extension_Core*: Defines all the core features of Twig. 337 338* *Twig_Extension_Escaper*: Adds automatic output-escaping and the possibility 339 to escape/unescape blocks of code. 340 341* *Twig_Extension_Sandbox*: Adds a sandbox mode to the default Twig 342 environment, making it safe to evaluate untrusted code. 343 344* *Twig_Extension_Profiler*: Enabled the built-in Twig profiler (as of Twig 345 1.18). 346 347* *Twig_Extension_Optimizer*: Optimizes the node tree before compilation. 348 349The core, escaper, and optimizer extensions do not need to be added to the 350Twig environment, as they are registered by default. 351 352Built-in Extensions 353------------------- 354 355This section describes the features added by the built-in extensions. 356 357.. tip:: 358 359 Read the chapter about extending Twig to learn how to create your own 360 extensions. 361 362Core Extension 363~~~~~~~~~~~~~~ 364 365The ``core`` extension defines all the core features of Twig: 366 367* :doc:`Tags <tags/index>`; 368* :doc:`Filters <filters/index>`; 369* :doc:`Functions <functions/index>`; 370* :doc:`Tests <tests/index>`. 371 372Escaper Extension 373~~~~~~~~~~~~~~~~~ 374 375The ``escaper`` extension adds automatic output escaping to Twig. It defines a 376tag, ``autoescape``, and a filter, ``raw``. 377 378When creating the escaper extension, you can switch on or off the global 379output escaping strategy:: 380 381 $escaper = new \Twig\Extension\EscaperExtension('html'); 382 $twig->addExtension($escaper); 383 384If set to ``html``, all variables in templates are escaped (using the ``html`` 385escaping strategy), except those using the ``raw`` filter: 386 387.. code-block:: jinja 388 389 {{ article.to_html|raw }} 390 391You can also change the escaping mode locally by using the ``autoescape`` tag 392(see the :doc:`autoescape<tags/autoescape>` doc for the syntax used before 393Twig 1.8): 394 395.. code-block:: jinja 396 397 {% autoescape 'html' %} 398 {{ var }} 399 {{ var|raw }} {# var won't be escaped #} 400 {{ var|escape }} {# var won't be double-escaped #} 401 {% endautoescape %} 402 403.. warning:: 404 405 The ``autoescape`` tag has no effect on included files. 406 407The escaping rules are implemented as follows: 408 409* Literals (integers, booleans, arrays, ...) used in the template directly as 410 variables or filter arguments are never automatically escaped: 411 412 .. code-block:: jinja 413 414 {{ "Twig<br />" }} {# won't be escaped #} 415 416 {% set text = "Twig<br />" %} 417 {{ text }} {# will be escaped #} 418 419* Expressions which the result is always a literal or a variable marked safe 420 are never automatically escaped: 421 422 .. code-block:: jinja 423 424 {{ foo ? "Twig<br />" : "<br />Twig" }} {# won't be escaped #} 425 426 {% set text = "Twig<br />" %} 427 {{ foo ? text : "<br />Twig" }} {# will be escaped #} 428 429 {% set text = "Twig<br />" %} 430 {{ foo ? text|raw : "<br />Twig" }} {# won't be escaped #} 431 432 {% set text = "Twig<br />" %} 433 {{ foo ? text|escape : "<br />Twig" }} {# the result of the expression won't be escaped #} 434 435* Escaping is applied before printing, after any other filter is applied: 436 437 .. code-block:: jinja 438 439 {{ var|upper }} {# is equivalent to {{ var|upper|escape }} #} 440 441* The `raw` filter should only be used at the end of the filter chain: 442 443 .. code-block:: jinja 444 445 {{ var|raw|upper }} {# will be escaped #} 446 447 {{ var|upper|raw }} {# won't be escaped #} 448 449* Automatic escaping is not applied if the last filter in the chain is marked 450 safe for the current context (e.g. ``html`` or ``js``). ``escape`` and 451 ``escape('html')`` are marked safe for HTML, ``escape('js')`` is marked 452 safe for JavaScript, ``raw`` is marked safe for everything. 453 454 .. code-block:: jinja 455 456 {% autoescape 'js' %} 457 {{ var|escape('html') }} {# will be escaped for HTML and JavaScript #} 458 {{ var }} {# will be escaped for JavaScript #} 459 {{ var|escape('js') }} {# won't be double-escaped #} 460 {% endautoescape %} 461 462.. note:: 463 464 Note that autoescaping has some limitations as escaping is applied on 465 expressions after evaluation. For instance, when working with 466 concatenation, ``{{ foo|raw ~ bar }}`` won't give the expected result as 467 escaping is applied on the result of the concatenation, not on the 468 individual variables (so, the ``raw`` filter won't have any effect here). 469 470Sandbox Extension 471~~~~~~~~~~~~~~~~~ 472 473The ``sandbox`` extension can be used to evaluate untrusted code. Access to 474unsafe attributes and methods is prohibited. The sandbox security is managed 475by a policy instance. By default, Twig comes with one policy class: 476``\Twig\Sandbox\SecurityPolicy``. This class allows you to white-list some 477tags, filters, properties, and methods:: 478 479 $tags = ['if']; 480 $filters = ['upper']; 481 $methods = [ 482 'Article' => ['getTitle', 'getBody'], 483 ]; 484 $properties = [ 485 'Article' => ['title', 'body'], 486 ]; 487 $functions = ['range']; 488 $policy = new \Twig\Sandbox\SecurityPolicy($tags, $filters, $methods, $properties, $functions); 489 490With the previous configuration, the security policy will only allow usage of 491the ``if`` tag, and the ``upper`` filter. Moreover, the templates will only be 492able to call the ``getTitle()`` and ``getBody()`` methods on ``Article`` 493objects, and the ``title`` and ``body`` public properties. Everything else 494won't be allowed and will generate a ``\Twig\Sandbox\SecurityError`` exception. 495 496The policy object is the first argument of the sandbox constructor:: 497 498 $sandbox = new \Twig\Extension\SandboxExtension($policy); 499 $twig->addExtension($sandbox); 500 501By default, the sandbox mode is disabled and should be enabled when including 502untrusted template code by using the ``sandbox`` tag: 503 504.. code-block:: jinja 505 506 {% sandbox %} 507 {% include 'user.html' %} 508 {% endsandbox %} 509 510You can sandbox all templates by passing ``true`` as the second argument of 511the extension constructor:: 512 513 $sandbox = new \Twig\Extension\SandboxExtension($policy, true); 514 515Profiler Extension 516~~~~~~~~~~~~~~~~~~ 517 518.. versionadded:: 1.18 519 The Profile extension was added in Twig 1.18. 520 521The ``profiler`` extension enables a profiler for Twig templates; it should 522only be used on your development machines as it adds some overhead:: 523 524 $profile = new \Twig\Profiler\Profile(); 525 $twig->addExtension(new \Twig\Extension\ProfilerExtension($profile)); 526 527 $dumper = new \Twig\Profiler\Dumper\TextDumper(); 528 echo $dumper->dump($profile); 529 530A profile contains information about time and memory consumption for template, 531block, and macro executions. 532 533You can also dump the data in a `Blackfire.io <https://blackfire.io/>`_ 534compatible format:: 535 536 $dumper = new \Twig\Profiler\Dumper\BlackfireDumper(); 537 file_put_contents('/path/to/profile.prof', $dumper->dump($profile)); 538 539Upload the profile to visualize it (create a `free account 540<https://blackfire.io/signup>`_ first): 541 542.. code-block:: sh 543 544 blackfire --slot=7 upload /path/to/profile.prof 545 546Optimizer Extension 547~~~~~~~~~~~~~~~~~~~ 548 549The ``optimizer`` extension optimizes the node tree before compilation:: 550 551 $twig->addExtension(new \Twig\Extension\OptimizerExtension()); 552 553By default, all optimizations are turned on. You can select the ones you want 554to enable by passing them to the constructor:: 555 556 $optimizer = new \Twig\Extension\OptimizerExtension(\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_FOR); 557 558 $twig->addExtension($optimizer); 559 560Twig supports the following optimizations: 561 562* ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_ALL``, enables all optimizations 563 (this is the default value). 564* ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_NONE``, disables all optimizations. 565 This reduces the compilation time, but it can increase the execution time 566 and the consumed memory. 567* ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_FOR``, optimizes the ``for`` tag by 568 removing the ``loop`` variable creation whenever possible. 569* ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_RAW_FILTER``, removes the ``raw`` 570 filter whenever possible. 571* ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_VAR_ACCESS``, simplifies the creation 572 and access of variables in the compiled templates whenever possible. 573 574Exceptions 575---------- 576 577Twig can throw exceptions: 578 579* ``\Twig\Error\Error``: The base exception for all errors. 580 581* ``\Twig\Error\SyntaxError``: Thrown to tell the user that there is a problem with 582 the template syntax. 583 584* ``\Twig\Error\RuntimeError``: Thrown when an error occurs at runtime (when a filter 585 does not exist for instance). 586 587* ``\Twig\Error\LoaderError``: Thrown when an error occurs during template loading. 588 589* ``\Twig\Sandbox\SecurityError``: Thrown when an unallowed tag, filter, or 590 method is called in a sandboxed template. 591