License

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.

Twig uses a central object called the environment (of class
\Twig\Environment). Instances of this class are used to store the
configuration and extensions, and are used to load templates from the file
system or other locations.

Most applications will create one \Twig\Environment object on application
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:

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.

When creating a new \Twig\Environment instance, you can pass an array of
options as the constructor second argument:

$twig=new\Twig\Environment($loader,['debug'=>true]);

The following options are available:

debugboolean

When set to true, the generated templates have a
__toString() method that you can use to display the generated nodes
(default to false).

charsetstring (defaults to utf-8)

The charset used by the templates.

base_template_classstring (defaults to \Twig\Template)

The base template class to use for generated
templates.

cachestring or false

An absolute path where to store the compiled templates, or
false to disable caching (which is the default).

auto_reloadboolean

When developing with Twig, it's useful to recompile the
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.

strict_variablesboolean

If set to false, Twig will silently ignore invalid
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).

autoescapestring

Sets the default auto-escaping strategy (name, html, js, css,
url, html_attr, or a PHP callback that takes the template "filename"
and returns the escaping strategy to use -- the callback cannot be a function
name to avoid collision with built-in escaping strategies); set it to
false to disable auto-escaping. The name escaping strategy 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.)

optimizationsinteger

A flag that indicates which optimizations to apply
(default to -1 -- all optimizations are enabled; set it to 0 to
disable).

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.
See the cache and auto_reload options of \Twig\Environment above
for more information.

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.

You can add or prepend paths via the addPath() and prependPath()
methods:

$loader->addPath($templateDir3);$loader->prependPath($templateDir4);

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):

$loader->addPath($templateDir,'admin');

Namespaced templates can be accessed via the special
@namespace_name/template_path notation:

$twig->render('@admin/index.html',[]);

\Twig\Loader\FilesystemLoader support absolute and relative paths. Using relative
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):

$loader=new\Twig\Loader\FilesystemLoader('templates',getcwd().'/..');

Note

When not passing the root path as a second argument, Twig uses getcwd()
for relative paths.

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.

Tip

When using the Array loader 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.

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.

interface\Twig\Loader\LoaderInterface{/** * Returns the source context for a given template logical name. * * @param string $name The template logical name * * @return \Twig\Source * * @throws \Twig\Error\LoaderError When $name is not found */publicfunctiongetSourceContext($name);/** * Gets the cache key to use for the cache for a given template name. * * @param string $name The name of the template to load * * @return string The cache key * * @throws \Twig\Error\LoaderError When $name is not found */publicfunctiongetCacheKey($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 * * @return bool true if the template is fresh, false otherwise * * @throws \Twig\Error\LoaderError When $name is not found */publicfunctionisFresh($name,$time);/** * Check if we have the source code of a template, given its name. * * @param string $name The name of the template to check if we can load * * @return bool If the template source code is handled by this loader or not */publicfunctionexists($name);}

The isFresh() method must return true if the current cached template
is still fresh, given the last modification time, or false otherwise.

The getSourceContext() method must return an instance of \Twig\Source.

Escaping is applied before printing, after any other filter is applied:

1

{{var|upper}}{# is equivalent to {{ var|upper|escape }} #}

The raw filter should only be used at the end of the filter chain:

1
2
3

{{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
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.

1
2
3
4
5

{%autoescape'js'%}{{var|escape('html')}}{# will be escaped for HTML and JavaScript #}{{var}}{# will be escaped for JavaScript #}{{var|escape('js')}}{# won't be double-escaped #}{%endautoescape%}

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).

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:
\Twig\Sandbox\SecurityPolicy. This class allows you to white-list some
tags, filters, properties, and methods:

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
won't be allowed and will generate a \Twig\Sandbox\SecurityError exception.