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.
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.
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
21 The simplest way to configure Twig to load templates for your application
22 looks roughly like this::
24 require_once '/path/to/lib/Twig/Autoloader.php';
25 Twig_Autoloader::register();
27 $loader = new Twig_Loader_Filesystem('/path/to/templates');
28 $twig = new Twig_Environment($loader, array(
29 'cache' => '/path/to/compilation_cache',
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.
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
49 To load a template from a Twig environment, call the ``load()`` method which
50 returns a ``Twig_TemplateWrapper`` instance::
52 $template = $twig->load('index.html');
56 Before Twig 1.28, you should use ``loadTemplate()`` instead which returns a
57 ``Twig_Template`` instance.
59 To render the template with some variables, call the ``render()`` method::
61 echo $template->render(array('the' => 'variables', 'go' => 'here'));
65 The ``display()`` method is a shortcut to output the template directly.
67 You can also load and render the template in one fell swoop::
69 echo $twig->render('index.html', array('the' => 'variables', 'go' => 'here'));
71 .. versionadded:: 1.28
72 The possibility to render blocks from the API was added in Twig 1.28.
74 If a template defines blocks, they can be rendered individually via the
75 ``renderBlock()`` call::
77 echo $template->renderBlock('block_name', array('the' => 'variables', 'go' => 'here'));
79 .. _environment_options:
84 When creating a new ``Twig_Environment`` instance, you can pass an array of
85 options as the constructor second argument::
87 $twig = new Twig_Environment($loader, array('debug' => true));
89 The following options are available:
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``).
97 * ``charset`` *string* (defaults to ``utf-8``)
99 The charset used by the templates.
101 * ``base_template_class`` *string* (defaults to ``Twig_Template``)
103 The base template class to use for generated
106 * ``cache`` *string* or ``false``
108 An absolute path where to store the compiled templates, or
109 ``false`` to disable caching (which is the default).
111 * ``auto_reload`` *boolean*
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
118 * ``strict_variables`` *boolean*
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``).
125 * ``autoescape`` *string* or *boolean*
127 If set to ``true``, HTML auto-escaping will be enabled by
128 default for all templates (default to ``true``).
130 As of Twig 1.8, you can set the escaping strategy to use (``html``, ``js``,
131 ``false`` to disable).
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).
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.)
143 * ``optimizations`` *integer*
145 A flag that indicates which optimizations to apply
146 (default to ``-1`` -- all optimizations are enabled; set it to ``0`` to
152 Loaders are responsible for loading templates from a resource such as the file
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.
167 Here is a list of the built-in loaders Twig provides:
169 ``Twig_Loader_Filesystem``
170 ..........................
172 .. versionadded:: 1.10
173 The ``prependPath()`` and support for namespaces were added in Twig 1.10.
175 .. versionadded:: 1.27
176 Relative paths support was added in Twig 1.27.
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
182 $loader = new Twig_Loader_Filesystem($templateDir);
184 It can also look for templates in an array of directories::
186 $loader = new Twig_Loader_Filesystem(array($templateDir1, $templateDir2));
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``.
192 You can add or prepend paths via the ``addPath()`` and ``prependPath()``
195 $loader->addPath($templateDir3);
196 $loader->prependPath($templateDir4);
198 The filesystem loader also supports namespaced templates. This allows to group
199 your templates under different namespaces which have their own template paths.
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)::
205 $loader->addPath($templateDir, 'admin');
207 Namespaced templates can be accessed via the special
208 ``@namespace_name/template_path`` notation::
210 $twig->render('@admin/index.html', array());
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)::
217 $loader = new Twig_Loader_Filesystem('templates', getcwd().'/..');
221 When not passing the root path as a second argument, Twig uses ``getcwd()``
224 ``Twig_Loader_Array``
225 .....................
227 ``Twig_Loader_Array`` loads a template from a PHP array. It's passed an array
228 of strings bound to template names::
230 $loader = new Twig_Loader_Array(array(
231 'index.html' => 'Hello {{ name }}!',
233 $twig = new Twig_Environment($loader);
235 echo $twig->render('index.html', array('name' => 'Fabien'));
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.
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.
248 ``Twig_Loader_Chain``
249 .....................
251 ``Twig_Loader_Chain`` delegates the loading of templates to other loaders::
253 $loader1 = new Twig_Loader_Array(array(
254 'base.html' => '{% block content %}{% endblock %}',
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',
261 $loader = new Twig_Loader_Chain(array($loader1, $loader2));
263 $twig = new Twig_Environment($loader);
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``.
270 ``Twig_Loader_Chain`` accepts any loader that implements
271 ``Twig_LoaderInterface``.
275 You can also add loaders via the ``addLoader()`` method.
277 Create your own Loader
278 ~~~~~~~~~~~~~~~~~~~~~~
280 All loaders implement the ``Twig_LoaderInterface``::
282 interface Twig_LoaderInterface
285 * Gets the source code of a template, given its name.
287 * @param string $name string The name of the template to load
289 * @return string The template source code
291 * @deprecated since 1.27 (to be removed in 2.0), implement Twig_SourceContextLoaderInterface
293 function getSource($name);
296 * Gets the cache key to use for the cache for a given template name.
298 * @param string $name string The name of the template to load
300 * @return string The cache key
302 function getCacheKey($name);
305 * Returns true if the template is still fresh.
307 * @param string $name The template name
308 * @param timestamp $time The last modification time of the cached template
310 function isFresh($name, $time);
313 The ``isFresh()`` method must return ``true`` if the current cached template
314 is still fresh, given the last modification time, or ``false`` otherwise.
318 As of Twig 1.27, you should also implement
319 ``Twig_SourceContextLoaderInterface`` to avoid deprecation notices.
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.
329 Twig extensions are packages that add new features to Twig. Using an
330 extension is as simple as using the ``addExtension()`` method::
332 $twig->addExtension(new Twig_Extension_Sandbox());
334 Twig comes bundled with the following extensions:
336 * *Twig_Extension_Core*: Defines all the core features of Twig.
338 * *Twig_Extension_Escaper*: Adds automatic output-escaping and the possibility
339 to escape/unescape blocks of code.
341 * *Twig_Extension_Sandbox*: Adds a sandbox mode to the default Twig
342 environment, making it safe to evaluate untrusted code.
344 * *Twig_Extension_Profiler*: Enabled the built-in Twig profiler (as of Twig
347 * *Twig_Extension_Optimizer*: Optimizes the node tree before compilation.
349 The core, escaper, and optimizer extensions do not need to be added to the
350 Twig environment, as they are registered by default.
355 This section describes the features added by the built-in extensions.
359 Read the chapter about extending Twig to learn how to create your own
365 The ``core`` extension defines all the core features of Twig:
367 * :doc:`Tags <tags/index>`;
368 * :doc:`Filters <filters/index>`;
369 * :doc:`Functions <functions/index>`;
370 * :doc:`Tests <tests/index>`.
375 The ``escaper`` extension adds automatic output escaping to Twig. It defines a
376 tag, ``autoescape``, and a filter, ``raw``.
378 When creating the escaper extension, you can switch on or off the global
379 output escaping strategy::
381 $escaper = new Twig_Extension_Escaper('html');
382 $twig->addExtension($escaper);
384 If set to ``html``, all variables in templates are escaped (using the ``html``
385 escaping strategy), except those using the ``raw`` filter:
387 .. code-block:: jinja
389 {{ article.to_html|raw }}
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
395 .. code-block:: jinja
397 {% autoescape 'html' %}
399 {{ var|raw }} {# var won't be escaped #}
400 {{ var|escape }} {# var won't be double-escaped #}
405 The ``autoescape`` tag has no effect on included files.
407 The escaping rules are implemented as follows:
409 * Literals (integers, booleans, arrays, ...) used in the template directly as
410 variables or filter arguments are never automatically escaped:
412 .. code-block:: jinja
414 {{ "Twig<br />" }} {# won't be escaped #}
416 {% set text = "Twig<br />" %}
417 {{ text }} {# will be escaped #}
419 * Expressions which the result is always a literal or a variable marked safe
420 are never automatically escaped:
422 .. code-block:: jinja
424 {{ foo ? "Twig<br />" : "<br />Twig" }} {# won't be escaped #}
426 {% set text = "Twig<br />" %}
427 {{ foo ? text : "<br />Twig" }} {# will be escaped #}
429 {% set text = "Twig<br />" %}
430 {{ foo ? text|raw : "<br />Twig" }} {# won't be escaped #}
432 {% set text = "Twig<br />" %}
433 {{ foo ? text|escape : "<br />Twig" }} {# the result of the expression won't be escaped #}
435 * Escaping is applied before printing, after any other filter is applied:
437 .. code-block:: jinja
439 {{ var|upper }} {# is equivalent to {{ var|upper|escape }} #}
441 * The `raw` filter should only be used at the end of the filter chain:
443 .. code-block:: jinja
445 {{ var|raw|upper }} {# will be escaped #}
447 {{ var|upper|raw }} {# won't be escaped #}
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.
454 .. code-block:: jinja
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 #}
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).
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::
480 $filters = array('upper');
482 'Article' => array('getTitle', 'getBody'),
485 'Article' => array('title', 'body'),
487 $functions = array('range');
488 $policy = new Twig_Sandbox_SecurityPolicy($tags, $filters, $methods, $properties, $functions);
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.
496 The policy object is the first argument of the sandbox constructor::
498 $sandbox = new Twig_Extension_Sandbox($policy);
499 $twig->addExtension($sandbox);
501 By default, the sandbox mode is disabled and should be enabled when including
502 untrusted template code by using the ``sandbox`` tag:
504 .. code-block:: jinja
507 {% include 'user.html' %}
510 You can sandbox all templates by passing ``true`` as the second argument of
511 the extension constructor::
513 $sandbox = new Twig_Extension_Sandbox($policy, true);
518 .. versionadded:: 1.18
519 The Profile extension was added in Twig 1.18.
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::
524 $profile = new Twig_Profiler_Profile();
525 $twig->addExtension(new Twig_Extension_Profiler($profile));
527 $dumper = new Twig_Profiler_Dumper_Text();
528 echo $dumper->dump($profile);
530 A profile contains information about time and memory consumption for template,
531 block, and macro executions.
533 You can also dump the data in a `Blackfire.io <https://blackfire.io/>`_
536 $dumper = new Twig_Profiler_Dumper_Blackfire();
537 file_put_contents('/path/to/profile.prof', $dumper->dump($profile));
539 Upload the profile to visualize it (create a `free account
540 <https://blackfire.io/signup>`_ first):
544 blackfire --slot=7 upload /path/to/profile.prof
549 The ``optimizer`` extension optimizes the node tree before compilation::
551 $twig->addExtension(new Twig_Extension_Optimizer());
553 By default, all optimizations are turned on. You can select the ones you want
554 to enable by passing them to the constructor::
556 $optimizer = new Twig_Extension_Optimizer(Twig_NodeVisitor_Optimizer::OPTIMIZE_FOR);
558 $twig->addExtension($optimizer);
560 Twig supports the following optimizations:
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.
577 Twig can throw exceptions:
579 * ``Twig_Error``: The base exception for all errors.
581 * ``Twig_Error_Syntax``: Thrown to tell the user that there is a problem with
584 * ``Twig_Error_Runtime``: Thrown when an error occurs at runtime (when a filter
585 does not exist for instance).
587 * ``Twig_Error_Loader``: Thrown when an error occurs during template loading.
589 * ``Twig_Sandbox_SecurityError``: Thrown when an unallowed tag, filter, or
590 method is called in a sandboxed template.