Security update for Core, with self-updated composer
[yaffs-website] / vendor / twig / twig / doc / api.rst
1 Twig for Developers
2 ===================
3
4 This chapter describes the API to Twig and not the template language. It will
5 be most useful as reference to those implementing the template interface to
6 the application and not those who are creating Twig templates.
7
8 Basics
9 ------
10
11 Twig uses a central object called the **environment** (of class
12 ``Twig_Environment``). Instances of this class are used to store the
13 configuration and extensions, and are used to load templates from the file
14 system or other locations.
15
16 Most applications will create one ``Twig_Environment`` object on application
17 initialization and use that to load templates. In some cases it's however
18 useful to have multiple environments side by side, if different configurations
19 are in use.
20
21 The simplest way to configure Twig to load templates for your application
22 looks roughly like this::
23
24     require_once '/path/to/lib/Twig/Autoloader.php';
25     Twig_Autoloader::register();
26
27     $loader = new Twig_Loader_Filesystem('/path/to/templates');
28     $twig = new Twig_Environment($loader, array(
29         'cache' => '/path/to/compilation_cache',
30     ));
31
32 This will create a template environment with the default settings and a loader
33 that looks up the templates in the ``/path/to/templates/`` folder. Different
34 loaders are available and you can also write your own if you want to load
35 templates 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
46 Rendering Templates
47 -------------------
48
49 To load a template from a Twig environment, call the ``load()`` method which
50 returns 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
59 To render the template with some variables, call the ``render()`` method::
60
61     echo $template->render(array('the' => 'variables', 'go' => 'here'));
62
63 .. note::
64
65     The ``display()`` method is a shortcut to output the template directly.
66
67 You can also load and render the template in one fell swoop::
68
69     echo $twig->render('index.html', array('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
74 If a template defines blocks, they can be rendered individually via the
75 ``renderBlock()`` call::
76
77     echo $template->renderBlock('block_name', array('the' => 'variables', 'go' => 'here'));
78
79 .. _environment_options:
80
81 Environment Options
82 -------------------
83
84 When creating a new ``Twig_Environment`` instance, you can pass an array of
85 options as the constructor second argument::
86
87     $twig = new Twig_Environment($loader, array('debug' => true));
88
89 The 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
149 Loaders
150 -------
151
152 Loaders are responsible for loading templates from a resource such as the file
153 system.
154
155 Compilation Cache
156 ~~~~~~~~~~~~~~~~~
157
158 All template loaders can cache the compiled templates on the filesystem for
159 future reuse. It speeds up Twig a lot as templates are only compiled once; and
160 the performance boost is even larger if you use a PHP accelerator such as APC.
161 See the ``cache`` and ``auto_reload`` options of ``Twig_Environment`` above
162 for more information.
163
164 Built-in Loaders
165 ~~~~~~~~~~~~~~~~
166
167 Here is a list of the built-in loaders Twig provides:
168
169 ``Twig_Loader_Filesystem``
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_Filesystem`` loads templates from the file system. This loader
179 can find templates in folders on the file system and is the preferred way to
180 load them::
181
182     $loader = new Twig_Loader_Filesystem($templateDir);
183
184 It can also look for templates in an array of directories::
185
186     $loader = new Twig_Loader_Filesystem(array($templateDir1, $templateDir2));
187
188 With 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
190 in the ``$templateDir2``.
191
192 You can add or prepend paths via the ``addPath()`` and ``prependPath()``
193 methods::
194
195     $loader->addPath($templateDir3);
196     $loader->prependPath($templateDir4);
197
198 The filesystem loader also supports namespaced templates. This allows to group
199 your templates under different namespaces which have their own template paths.
200
201 When using the ``setPaths()``, ``addPath()``, and ``prependPath()`` methods,
202 specify the namespace as the second argument (when not specified, these
203 methods act on the "main" namespace)::
204
205     $loader->addPath($templateDir, 'admin');
206
207 Namespaced templates can be accessed via the special
208 ``@namespace_name/template_path`` notation::
209
210     $twig->render('@admin/index.html', array());
211
212 ``Twig_Loader_Filesystem`` support absolute and relative paths. Using relative
213 paths is preferred as it makes the cache keys independent of the project root
214 directory (for instance, it allows warming the cache from a build server where
215 the directory might be different from the one used on production servers)::
216
217     $loader = new Twig_Loader_Filesystem('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_Array``
225 .....................
226
227 ``Twig_Loader_Array`` loads a template from a PHP array. It's passed an array
228 of strings bound to template names::
229
230     $loader = new Twig_Loader_Array(array(
231         'index.html' => 'Hello {{ name }}!',
232     ));
233     $twig = new Twig_Environment($loader);
234
235     echo $twig->render('index.html', array('name' => 'Fabien'));
236
237 This loader is very useful for unit testing. It can also be used for small
238 projects 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_Chain``
249 .....................
250
251 ``Twig_Loader_Chain`` delegates the loading of templates to other loaders::
252
253     $loader1 = new Twig_Loader_Array(array(
254         'base.html' => '{% block content %}{% endblock %}',
255     ));
256     $loader2 = new Twig_Loader_Array(array(
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_Chain(array($loader1, $loader2));
262
263     $twig = new Twig_Environment($loader);
264
265 When looking for a template, Twig will try each loader in turn and it will
266 return as soon as the template is found. When rendering the ``index.html``
267 template 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_Chain`` accepts any loader that implements
271 ``Twig_LoaderInterface``.
272
273 .. note::
274
275     You can also add loaders via the ``addLoader()`` method.
276
277 Create your own Loader
278 ~~~~~~~~~~~~~~~~~~~~~~
279
280 All loaders implement the ``Twig_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_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
313 The ``isFresh()`` method must return ``true`` if the current cached template
314 is 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_SourceContextLoaderInterface`` to avoid deprecation notices.
320
321 .. tip::
322
323     As of Twig 1.11.0, you can also implement ``Twig_ExistsLoaderInterface``
324     to make your loader faster when used with the chain loader.
325
326 Using Extensions
327 ----------------
328
329 Twig extensions are packages that add new features to Twig. Using an
330 extension is as simple as using the ``addExtension()`` method::
331
332     $twig->addExtension(new Twig_Extension_Sandbox());
333
334 Twig 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
349 The core, escaper, and optimizer extensions do not need to be added to the
350 Twig environment, as they are registered by default.
351
352 Built-in Extensions
353 -------------------
354
355 This 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
362 Core Extension
363 ~~~~~~~~~~~~~~
364
365 The ``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
372 Escaper Extension
373 ~~~~~~~~~~~~~~~~~
374
375 The ``escaper`` extension adds automatic output escaping to Twig. It defines a
376 tag, ``autoescape``, and a filter, ``raw``.
377
378 When creating the escaper extension, you can switch on or off the global
379 output escaping strategy::
380
381     $escaper = new Twig_Extension_Escaper('html');
382     $twig->addExtension($escaper);
383
384 If set to ``html``, all variables in templates are escaped (using the ``html``
385 escaping strategy), except those using the ``raw`` filter:
386
387 .. code-block:: jinja
388
389     {{ article.to_html|raw }}
390
391 You 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
393 Twig 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
407 The 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
470 Sandbox Extension
471 ~~~~~~~~~~~~~~~~~
472
473 The ``sandbox`` extension can be used to evaluate untrusted code. Access to
474 unsafe attributes and methods is prohibited. The sandbox security is managed
475 by a policy instance. By default, Twig comes with one policy class:
476 ``Twig_Sandbox_SecurityPolicy``. This class allows you to white-list some
477 tags, filters, properties, and methods::
478
479     $tags = array('if');
480     $filters = array('upper');
481     $methods = array(
482         'Article' => array('getTitle', 'getBody'),
483     );
484     $properties = array(
485         'Article' => array('title', 'body'),
486     );
487     $functions = array('range');
488     $policy = new Twig_Sandbox_SecurityPolicy($tags, $filters, $methods, $properties, $functions);
489
490 With the previous configuration, the security policy will only allow usage of
491 the ``if`` tag, and the ``upper`` filter. Moreover, the templates will only be
492 able to call the ``getTitle()`` and ``getBody()`` methods on ``Article``
493 objects, and the ``title`` and ``body`` public properties. Everything else
494 won't be allowed and will generate a ``Twig_Sandbox_SecurityError`` exception.
495
496 The policy object is the first argument of the sandbox constructor::
497
498     $sandbox = new Twig_Extension_Sandbox($policy);
499     $twig->addExtension($sandbox);
500
501 By default, the sandbox mode is disabled and should be enabled when including
502 untrusted template code by using the ``sandbox`` tag:
503
504 .. code-block:: jinja
505
506     {% sandbox %}
507         {% include 'user.html' %}
508     {% endsandbox %}
509
510 You can sandbox all templates by passing ``true`` as the second argument of
511 the extension constructor::
512
513     $sandbox = new Twig_Extension_Sandbox($policy, true);
514
515 Profiler Extension
516 ~~~~~~~~~~~~~~~~~~
517
518 .. versionadded:: 1.18
519     The Profile extension was added in Twig 1.18.
520
521 The ``profiler`` extension enables a profiler for Twig templates; it should
522 only be used on your development machines as it adds some overhead::
523
524     $profile = new Twig_Profiler_Profile();
525     $twig->addExtension(new Twig_Extension_Profiler($profile));
526
527     $dumper = new Twig_Profiler_Dumper_Text();
528     echo $dumper->dump($profile);
529
530 A profile contains information about time and memory consumption for template,
531 block, and macro executions.
532
533 You can also dump the data in a `Blackfire.io <https://blackfire.io/>`_
534 compatible format::
535
536     $dumper = new Twig_Profiler_Dumper_Blackfire();
537     file_put_contents('/path/to/profile.prof', $dumper->dump($profile));
538
539 Upload 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
546 Optimizer Extension
547 ~~~~~~~~~~~~~~~~~~~
548
549 The ``optimizer`` extension optimizes the node tree before compilation::
550
551     $twig->addExtension(new Twig_Extension_Optimizer());
552
553 By default, all optimizations are turned on. You can select the ones you want
554 to enable by passing them to the constructor::
555
556     $optimizer = new Twig_Extension_Optimizer(Twig_NodeVisitor_Optimizer::OPTIMIZE_FOR);
557
558     $twig->addExtension($optimizer);
559
560 Twig supports the following optimizations:
561
562 * ``Twig_NodeVisitor_Optimizer::OPTIMIZE_ALL``, enables all optimizations
563   (this is the default value).
564 * ``Twig_NodeVisitor_Optimizer::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_Optimizer::OPTIMIZE_FOR``, optimizes the ``for`` tag by
568   removing the ``loop`` variable creation whenever possible.
569 * ``Twig_NodeVisitor_Optimizer::OPTIMIZE_RAW_FILTER``, removes the ``raw``
570   filter whenever possible.
571 * ``Twig_NodeVisitor_Optimizer::OPTIMIZE_VAR_ACCESS``, simplifies the creation
572   and access of variables in the compiled templates whenever possible.
573
574 Exceptions
575 ----------
576
577 Twig can throw exceptions:
578
579 * ``Twig_Error``: The base exception for all errors.
580
581 * ``Twig_Error_Syntax``: Thrown to tell the user that there is a problem with
582   the template syntax.
583
584 * ``Twig_Error_Runtime``: Thrown when an error occurs at runtime (when a filter
585   does not exist for instance).
586
587 * ``Twig_Error_Loader``: 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.