doc/api.rst
a855b189
 Twig for Developers
 ===================
 
 This chapter describes the API to Twig and not the template language. It will
 be most useful as reference to those implementing the template interface to
 the application and not those who are creating Twig templates.
 
 Basics
 ------
 
 Twig uses a central object called the **environment** (of class
3632a46e
 ``\Twig\Environment``). Instances of this class are used to store the
a855b189
 configuration and extensions, and are used to load templates from the file
 system or other locations.
 
3632a46e
 Most applications will create one ``\Twig\Environment`` object on application
a855b189
 initialization and use that to load templates. In some cases it's however
 useful to have multiple environments side by side, if different configurations
 are in use.
 
 The simplest way to configure Twig to load templates for your application
 looks roughly like this::
 
     require_once '/path/to/lib/Twig/Autoloader.php';
     Twig_Autoloader::register();
 
3632a46e
     $loader = new \Twig\Loader\FilesystemLoader('/path/to/templates');
     $twig = new \Twig\Environment($loader, [
d65366e7
         'cache' => '/path/to/compilation_cache',
a2c42534
     ]);
a855b189
 
 This will create a template environment with the default settings and a loader
 that looks up the templates in the ``/path/to/templates/`` folder. Different
 loaders are available and you can also write your own if you want to load
 templates from a database or other resources.
 
 .. note::
 
     Notice that the second argument of the environment is an array of options.
     The ``cache`` option is a compilation cache directory, where Twig caches
     the compiled templates to avoid the parsing phase for sub-sequent
     requests. It is very different from the cache you might want to add for
     the evaluated templates. For such a need, you can use any available PHP
     cache library.
 
d7062f35
 Rendering Templates
 -------------------
 
 To load a template from a Twig environment, call the ``load()`` method which
3632a46e
 returns a ``\Twig\TemplateWrapper`` instance::
d7062f35
 
     $template = $twig->load('index.html');
 
 .. note::
a855b189
 
d7062f35
     Before Twig 1.28, you should use ``loadTemplate()`` instead which returns a
3632a46e
     ``\Twig\Template`` instance.
a855b189
 
 To render the template with some variables, call the ``render()`` method::
 
a2c42534
     echo $template->render(['the' => 'variables', 'go' => 'here']);
a855b189
 
 .. note::
 
     The ``display()`` method is a shortcut to output the template directly.
 
d65366e7
 You can also load and render the template in one fell swoop::
 
a2c42534
     echo $twig->render('index.html', ['the' => 'variables', 'go' => 'here']);
d65366e7
 
d7062f35
 .. versionadded:: 1.28
     The possibility to render blocks from the API was added in Twig 1.28.
 
 If a template defines blocks, they can be rendered individually via the
 ``renderBlock()`` call::
 
a2c42534
     echo $template->renderBlock('block_name', ['the' => 'variables', 'go' => 'here']);
d7062f35
 
fbacbe60
 .. _environment_options:
 
a855b189
 Environment Options
 -------------------
 
3632a46e
 When creating a new ``\Twig\Environment`` instance, you can pass an array of
a855b189
 options as the constructor second argument::
 
3632a46e
     $twig = new \Twig\Environment($loader, ['debug' => true]);
a855b189
 
 The following options are available:
 
0a46d060
 * ``debug`` *boolean*
 
   When set to ``true``, the generated templates have a
a855b189
   ``__toString()`` method that you can use to display the generated nodes
   (default to ``false``).
 
b42ddb39
 * ``charset`` *string* (defaults to ``utf-8``)
0a46d060
 
   The charset used by the templates.
 
3632a46e
 * ``base_template_class`` *string* (defaults to ``\Twig\Template``)
0a46d060
 
   The base template class to use for generated
   templates.
a855b189
 
b42ddb39
 * ``cache`` *string* or ``false``
a855b189
 
0a46d060
   An absolute path where to store the compiled templates, or
a855b189
   ``false`` to disable caching (which is the default).
 
0a46d060
 * ``auto_reload`` *boolean*
 
   When developing with Twig, it's useful to recompile the
a855b189
   template whenever the source code changes. If you don't provide a value for
   the ``auto_reload`` option, it will be determined automatically based on the
   ``debug`` value.
 
0a46d060
 * ``strict_variables`` *boolean*
 
   If set to ``false``, Twig will silently ignore invalid
3cbcc1f4
   variables (variables and or attributes/methods that do not exist) and
   replace them with a ``null`` value. When set to ``true``, Twig throws an
   exception instead (default to ``false``).
a855b189
 
b42ddb39
 * ``autoescape`` *string* or *boolean*
0a46d060
 
   If set to ``true``, HTML auto-escaping will be enabled by
01ab6f31
   default for all templates (default to ``true``).
 
   As of Twig 1.8, you can set the escaping strategy to use (``html``, ``js``,
   ``false`` to disable).
 
   As of Twig 1.9, you can set the escaping strategy to use (``css``, ``url``,
3c764b2b
   ``html_attr``, or a PHP callback that takes the template name and must
bee4cd12
   return the escaping strategy to use -- the callback cannot be a function name
01ab6f31
   to avoid collision with built-in escaping strategies).
 
3c764b2b
   As of Twig 1.17, the ``filename`` escaping strategy (renamed to ``name`` as
   of Twig 1.27) determines the escaping strategy to use for a template based on
   the template filename extension (this strategy does not incur any overhead at
   runtime as auto-escaping is done at compilation time.)
a855b189
 
0a46d060
 * ``optimizations`` *integer*
 
   A flag that indicates which optimizations to apply
3cbcc1f4
   (default to ``-1`` -- all optimizations are enabled; set it to ``0`` to
   disable).
a855b189
 
 Loaders
 -------
 
 Loaders are responsible for loading templates from a resource such as the file
 system.
 
 Compilation Cache
 ~~~~~~~~~~~~~~~~~
 
 All template loaders can cache the compiled templates on the filesystem for
 future reuse. It speeds up Twig a lot as templates are only compiled once; and
 the performance boost is even larger if you use a PHP accelerator such as APC.
3632a46e
 See the ``cache`` and ``auto_reload`` options of ``\Twig\Environment`` above
a855b189
 for more information.
 
 Built-in Loaders
 ~~~~~~~~~~~~~~~~
 
 Here is a list of the built-in loaders Twig provides:
 
3632a46e
 ``\Twig\Loader\FilesystemLoader``
eaa29417
 .................................
a855b189
 
c38e06ff
 .. versionadded:: 1.10
     The ``prependPath()`` and support for namespaces were added in Twig 1.10.
 
a343c928
 .. versionadded:: 1.27
     Relative paths support was added in Twig 1.27.
 
3632a46e
 ``\Twig\Loader\FilesystemLoader`` loads templates from the file system. This loader
17e2c36a
 can find templates in folders on the file system and is the preferred way to
 load them::
a855b189
 
3632a46e
     $loader = new \Twig\Loader\FilesystemLoader($templateDir);
a855b189
 
17e2c36a
 It can also look for templates in an array of directories::
a855b189
 
3632a46e
     $loader = new \Twig\Loader\FilesystemLoader([$templateDir1, $templateDir2]);
a855b189
 
17e2c36a
 With such a configuration, Twig will first look for templates in
 ``$templateDir1`` and if they do not exist, it will fallback to look for them
 in the ``$templateDir2``.
a855b189
 
c24ea1bc
 You can add or prepend paths via the ``addPath()`` and ``prependPath()``
 methods::
 
     $loader->addPath($templateDir3);
     $loader->prependPath($templateDir4);
 
94260724
 The filesystem loader also supports namespaced templates. This allows to group
 your templates under different namespaces which have their own template paths.
 
 When using the ``setPaths()``, ``addPath()``, and ``prependPath()`` methods,
 specify the namespace as the second argument (when not specified, these
 methods act on the "main" namespace)::
0eb4d01d
 
     $loader->addPath($templateDir, 'admin');
 
94260724
 Namespaced templates can be accessed via the special
 ``@namespace_name/template_path`` notation::
0eb4d01d
 
a2c42534
     $twig->render('@admin/index.html', []);
0eb4d01d
 
3632a46e
 ``\Twig\Loader\FilesystemLoader`` support absolute and relative paths. Using relative
a343c928
 paths is preferred as it makes the cache keys independent of the project root
 directory (for instance, it allows warming the cache from a build server where
 the directory might be different from the one used on production servers)::
 
3632a46e
     $loader = new \Twig\Loader\FilesystemLoader('templates', getcwd().'/..');
a343c928
 
 .. note::
 
     When not passing the root path as a second argument, Twig uses ``getcwd()``
     for relative paths.
 
3632a46e
 ``\Twig\Loader\ArrayLoader``
eaa29417
 ............................
a855b189
 
3632a46e
 ``\Twig\Loader\ArrayLoader`` loads a template from a PHP array. It's passed an array
17e2c36a
 of strings bound to template names::
 
3632a46e
     $loader = new \Twig\Loader\ArrayLoader([
17e2c36a
         'index.html' => 'Hello {{ name }}!',
a2c42534
     ]);
3632a46e
     $twig = new \Twig\Environment($loader);
17e2c36a
 
a2c42534
     echo $twig->render('index.html', ['name' => 'Fabien']);
17e2c36a
 
 This loader is very useful for unit testing. It can also be used for small
 projects where storing all templates in a single PHP file might make sense.
a855b189
 
 .. tip::
 
     When using the ``Array`` or ``String`` loaders with a cache mechanism, you
     should know that a new cache key is generated each time a template content
     "changes" (the cache key being the source code of the template). If you
     don't want to see your cache grows out of control, you need to take care
     of clearing the old cache file by yourself.
 
3632a46e
 ``\Twig\Loader\ChainLoader``
eaa29417
 ............................
d59642c9
 
3632a46e
 ``\Twig\Loader\ChainLoader`` delegates the loading of templates to other loaders::
d59642c9
 
3632a46e
     $loader1 = new \Twig\Loader\ArrayLoader([
d59642c9
         'base.html' => '{% block content %}{% endblock %}',
a2c42534
     ]);
3632a46e
     $loader2 = new \Twig\Loader\ArrayLoader([
882f44b0
         'index.html' => '{% extends "base.html" %}{% block content %}Hello {{ name }}{% endblock %}',
d59642c9
         'base.html'  => 'Will never be loaded',
a2c42534
     ]);
d59642c9
 
3632a46e
     $loader = new \Twig\Loader\ChainLoader([$loader1, $loader2]);
d59642c9
 
3632a46e
     $twig = new \Twig\Environment($loader);
d59642c9
 
 When looking for a template, Twig will try each loader in turn and it will
 return as soon as the template is found. When rendering the ``index.html``
 template from the above example, Twig will load it with ``$loader2`` but the
 ``base.html`` template will be loaded from ``$loader1``.
 
3632a46e
 ``\Twig\Loader\ChainLoader`` accepts any loader that implements
 ``\Twig\Loader\LoaderInterface``.
d59642c9
 
 .. note::
 
     You can also add loaders via the ``addLoader()`` method.
 
a855b189
 Create your own Loader
 ~~~~~~~~~~~~~~~~~~~~~~
 
3632a46e
 All loaders implement the ``\Twig\Loader\LoaderInterface``::
a855b189
 
     interface Twig_LoaderInterface
     {
         /**
          * Gets the source code of a template, given its name.
          *
          * @param  string $name string The name of the template to load
          *
          * @return string The template source code
21ecba8c
          *
db751d62
          * @deprecated since 1.27 (to be removed in 2.0), implement \Twig\Loader\SourceContextLoaderInterface
a855b189
          */
         function getSource($name);
 
         /**
          * Gets the cache key to use for the cache for a given template name.
          *
          * @param  string $name string The name of the template to load
          *
          * @return string The cache key
          */
         function getCacheKey($name);
 
         /**
          * Returns true if the template is still fresh.
          *
          * @param string    $name The template name
          * @param timestamp $time The last modification time of the cached template
          */
         function isFresh($name, $time);
     }
 
 The ``isFresh()`` method must return ``true`` if the current cached template
 is still fresh, given the last modification time, or ``false`` otherwise.
 
21ecba8c
 .. note::
 
     As of Twig 1.27, you should also implement
3632a46e
     ``\Twig\Loader\SourceContextLoaderInterface`` to avoid deprecation notices.
21ecba8c
 
244eaf53
 .. tip::
 
3632a46e
     As of Twig 1.11.0, you can also implement ``\Twig\Loader\ExistsLoaderInterface``
244eaf53
     to make your loader faster when used with the chain loader.
 
a855b189
 Using Extensions
 ----------------
 
522f35ed
 Twig extensions are packages that add new features to Twig. Using an
a855b189
 extension is as simple as using the ``addExtension()`` method::
 
3632a46e
     $twig->addExtension(new \Twig\Extension\SandboxExtension());
a855b189
 
 Twig comes bundled with the following extensions:
 
522f35ed
 * *Twig_Extension_Core*: Defines all the core features of Twig.
a855b189
 
 * *Twig_Extension_Escaper*: Adds automatic output-escaping and the possibility
   to escape/unescape blocks of code.
 
 * *Twig_Extension_Sandbox*: Adds a sandbox mode to the default Twig
aac6cb61
   environment, making it safe to evaluate untrusted code.
a855b189
 
4408caae
 * *Twig_Extension_Profiler*: Enabled the built-in Twig profiler (as of Twig
   1.18).
 
aac6cb61
 * *Twig_Extension_Optimizer*: Optimizes the node tree before compilation.
a855b189
 
 The core, escaper, and optimizer extensions do not need to be added to the
0a7b37b8
 Twig environment, as they are registered by default.
a855b189
 
 Built-in Extensions
 -------------------
 
 This section describes the features added by the built-in extensions.
 
 .. tip::
 
     Read the chapter about extending Twig to learn how to create your own
     extensions.
 
 Core Extension
 ~~~~~~~~~~~~~~
 
 The ``core`` extension defines all the core features of Twig:
 
81af6a1f
 * :doc:`Tags <tags/index>`;
 * :doc:`Filters <filters/index>`;
 * :doc:`Functions <functions/index>`;
 * :doc:`Tests <tests/index>`.
522f35ed
 
a855b189
 Escaper Extension
 ~~~~~~~~~~~~~~~~~
 
 The ``escaper`` extension adds automatic output escaping to Twig. It defines a
3697ef4a
 tag, ``autoescape``, and a filter, ``raw``.
a855b189
 
 When creating the escaper extension, you can switch on or off the global
 output escaping strategy::
 
3632a46e
     $escaper = new \Twig\Extension\EscaperExtension('html');
a855b189
     $twig->addExtension($escaper);
 
12a5d026
 If set to ``html``, all variables in templates are escaped (using the ``html``
2a2aeee8
 escaping strategy), except those using the ``raw`` filter:
a855b189
 
 .. code-block:: jinja
 
     {{ article.to_html|raw }}
 
75d97b4a
 You can also change the escaping mode locally by using the ``autoescape`` tag
5923f0cb
 (see the :doc:`autoescape<tags/autoescape>` doc for the syntax used before
75d97b4a
 Twig 1.8):
a855b189
 
 .. code-block:: jinja
 
75d97b4a
     {% autoescape 'html' %}
3697ef4a
         {{ var }}
         {{ var|raw }}      {# var won't be escaped #}
         {{ var|escape }}   {# var won't be double-escaped #}
a855b189
     {% endautoescape %}
 
 .. warning::
 
     The ``autoescape`` tag has no effect on included files.
 
3cbcc1f4
 The escaping rules are implemented as follows:
a855b189
 
 * Literals (integers, booleans, arrays, ...) used in the template directly as
   variables or filter arguments are never automatically escaped:
 
   .. code-block:: jinja
 
         {{ "Twig<br />" }} {# won't be escaped #}
 
         {% set text = "Twig<br />" %}
         {{ text }} {# will be escaped #}
 
 * Expressions which the result is always a literal or a variable marked safe
   are never automatically escaped:
 
   .. code-block:: jinja
 
         {{ foo ? "Twig<br />" : "<br />Twig" }} {# won't be escaped #}
 
         {% set text = "Twig<br />" %}
         {{ foo ? text : "<br />Twig" }} {# will be escaped #}
 
         {% set text = "Twig<br />" %}
         {{ foo ? text|raw : "<br />Twig" }} {# won't be escaped #}
 
         {% set text = "Twig<br />" %}
         {{ foo ? text|escape : "<br />Twig" }} {# the result of the expression won't be escaped #}
 
 * Escaping is applied before printing, after any other filter is applied:
 
   .. code-block:: jinja
 
         {{ var|upper }} {# is equivalent to {{ var|upper|escape }} #}
 
 * The `raw` filter should only be used at the end of the filter chain:
 
   .. code-block:: jinja
 
         {{ var|raw|upper }} {# will be escaped #}
 
         {{ var|upper|raw }} {# won't be escaped #}
 
 * Automatic escaping is not applied if the last filter in the chain is marked
a21df952
   safe for the current context (e.g. ``html`` or ``js``). ``escape`` and
   ``escape('html')`` are marked safe for HTML, ``escape('js')`` is marked
   safe for JavaScript, ``raw`` is marked safe for everything.
a855b189
 
   .. code-block:: jinja
 
18810458
         {% autoescape 'js' %}
a21df952
             {{ var|escape('html') }} {# will be escaped for HTML and JavaScript #}
             {{ var }} {# will be escaped for JavaScript #}
18810458
             {{ var|escape('js') }} {# won't be double-escaped #}
a855b189
         {% endautoescape %}
 
c456666b
 .. note::
 
     Note that autoescaping has some limitations as escaping is applied on
     expressions after evaluation. For instance, when working with
     concatenation, ``{{ foo|raw ~ bar }}`` won't give the expected result as
     escaping is applied on the result of the concatenation, not on the
     individual variables (so, the ``raw`` filter won't have any effect here).
 
a855b189
 Sandbox Extension
 ~~~~~~~~~~~~~~~~~
 
 The ``sandbox`` extension can be used to evaluate untrusted code. Access to
 unsafe attributes and methods is prohibited. The sandbox security is managed
 by a policy instance. By default, Twig comes with one policy class:
3632a46e
 ``\Twig\Sandbox\SecurityPolicy``. This class allows you to white-list some
a855b189
 tags, filters, properties, and methods::
 
a2c42534
     $tags = ['if'];
     $filters = ['upper'];
     $methods = [
         'Article' => ['getTitle', 'getBody'],
     ];
     $properties = [
         'Article' => ['title', 'body'],
     ];
     $functions = ['range'];
3632a46e
     $policy = new \Twig\Sandbox\SecurityPolicy($tags, $filters, $methods, $properties, $functions);
a855b189
 
 With the previous configuration, the security policy will only allow usage of
 the ``if`` tag, and the ``upper`` filter. Moreover, the templates will only be
 able to call the ``getTitle()`` and ``getBody()`` methods on ``Article``
 objects, and the ``title`` and ``body`` public properties. Everything else
3632a46e
 won't be allowed and will generate a ``\Twig\Sandbox\SecurityError`` exception.
a855b189
 
 The policy object is the first argument of the sandbox constructor::
 
3632a46e
     $sandbox = new \Twig\Extension\SandboxExtension($policy);
a855b189
     $twig->addExtension($sandbox);
 
 By default, the sandbox mode is disabled and should be enabled when including
 untrusted template code by using the ``sandbox`` tag:
 
 .. code-block:: jinja
 
     {% sandbox %}
         {% include 'user.html' %}
     {% endsandbox %}
 
 You can sandbox all templates by passing ``true`` as the second argument of
 the extension constructor::
 
3632a46e
     $sandbox = new \Twig\Extension\SandboxExtension($policy, true);
a855b189
 
4408caae
 Profiler Extension
 ~~~~~~~~~~~~~~~~~~
 
 .. versionadded:: 1.18
     The Profile extension was added in Twig 1.18.
 
 The ``profiler`` extension enables a profiler for Twig templates; it should
 only be used on your development machines as it adds some overhead::
 
3632a46e
     $profile = new \Twig\Profiler\Profile();
     $twig->addExtension(new \Twig\Extension\ProfilerExtension($profile));
4408caae
 
3632a46e
     $dumper = new \Twig\Profiler\Dumper\TextDumper();
4408caae
     echo $dumper->dump($profile);
 
 A profile contains information about time and memory consumption for template,
 block, and macro executions.
 
 You can also dump the data in a `Blackfire.io <https://blackfire.io/>`_
 compatible format::
 
3632a46e
     $dumper = new \Twig\Profiler\Dumper\BlackfireDumper();
4408caae
     file_put_contents('/path/to/profile.prof', $dumper->dump($profile));
 
 Upload the profile to visualize it (create a `free account
 <https://blackfire.io/signup>`_ first):
 
 .. code-block:: sh
 
     blackfire --slot=7 upload /path/to/profile.prof
 
3cbcc1f4
 Optimizer Extension
 ~~~~~~~~~~~~~~~~~~~
a855b189
 
 The ``optimizer`` extension optimizes the node tree before compilation::
 
3632a46e
     $twig->addExtension(new \Twig\Extension\OptimizerExtension());
a855b189
 
 By default, all optimizations are turned on. You can select the ones you want
 to enable by passing them to the constructor::
 
3632a46e
     $optimizer = new \Twig\Extension\OptimizerExtension(\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_FOR);
a855b189
 
     $twig->addExtension($optimizer);
 
aac6cb61
 Twig supports the following optimizations:
 
3632a46e
 * ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_ALL``, enables all optimizations
fd964307
   (this is the default value).
3632a46e
 * ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_NONE``, disables all optimizations.
fd964307
   This reduces the compilation time, but it can increase the execution time
   and the consumed memory.
3632a46e
 * ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_FOR``, optimizes the ``for`` tag by
fd964307
   removing the ``loop`` variable creation whenever possible.
3632a46e
 * ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_RAW_FILTER``, removes the ``raw``
fd964307
   filter whenever possible.
3632a46e
 * ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_VAR_ACCESS``, simplifies the creation
fd964307
   and access of variables in the compiled templates whenever possible.
aac6cb61
 
a855b189
 Exceptions
 ----------
 
 Twig can throw exceptions:
 
3632a46e
 * ``\Twig\Error\Error``: The base exception for all errors.
a855b189
 
3632a46e
 * ``\Twig\Error\SyntaxError``: Thrown to tell the user that there is a problem with
a855b189
   the template syntax.
 
3632a46e
 * ``\Twig\Error\RuntimeError``: Thrown when an error occurs at runtime (when a filter
a855b189
   does not exist for instance).
 
3632a46e
 * ``\Twig\Error\LoaderError``: Thrown when an error occurs during template loading.
9dcf64e3
 
3632a46e
 * ``\Twig\Sandbox\SecurityError``: Thrown when an unallowed tag, filter, or
a855b189
   method is called in a sandboxed template.