# Twig for Developers
This chapter describes the API to Twig and not the template language. It willbe most useful as reference to those implementing the template interface tothe application and not those who are creating Twig templates.
### Basics
Twig uses a central object called the **environment** (of class`Twig_Environment`). Instances of this class are used to store theconfiguration and extensions, and are used to load templates from the filesystem or other locations.
Most applications will create one `Twig_Environment` object on applicationinitialization and use that to load templates. In some cases it's howeveruseful to have multiple environments side by side, if different configurationsare in use.
The simplest way to configure Twig to load templates for your applicationlooks roughly like this:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4
5
6
7</pre></div></td><td class="code"><div class="highlight"><pre>require_once '/path/to/lib/Twig/Autoloader.php';
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem('/path/to/templates');
$twig = new Twig_Environment($loader, array(
'cache' => '/path/to/compilation_cache',
));
</pre></div></td></tr></table>
This will create a template environment with the default settings and a loaderthat looks up the templates in the `/path/to/templates/` folder. Differentloaders are available and you can also write your own if you want to loadtemplates 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 cachesthe compiled templates to avoid the parsing phase for sub-sequentrequests. It is very different from the cache you might want to add forthe evaluated templates. For such a need, you can use any available PHPcache library.
To load a template from this environment you just have to call the`loadTemplate()` method which then returns a `Twig_Template` instance:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>$template = $twig->loadTemplate('index.html');
</pre></div></td></tr></table>
To render the template with some variables, call the `render()` method:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>echo $template->render(array('the' => 'variables', 'go' => 'here'));
</pre></div></td></tr></table>
Note
The `display()` method is a shortcut to output the template directly.
You can also load and render the template in one fell swoop:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>echo $twig->render('index.html', array('the' => 'variables', 'go' => 'here'));
</pre></div></td></tr></table>
### Environment Options
When creating a new `Twig_Environment` instance, you can pass an array ofoptions as the constructor second argument:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>$twig = new Twig_Environment($loader, array('debug' => true));
</pre></div></td></tr></table>
The following options are available:
-
`debug`*boolean*
When set to `true`, the generated templates have a`__toString()` method that you can use to display the generated nodes(default to `false`).
-
`charset`*string (default to ``utf-8``)*
The charset used by the templates.
-
`base_template_class`*string (default to ``Twig_Template``)*
The base template class to use for generatedtemplates.
-
`cache`*string|false*
An absolute path where to store the compiled templates, or`false` to disable caching (which is the default).
-
`auto_reload`*boolean*
When developing with Twig, it's useful to recompile thetemplate whenever the source code changes. If you don't provide a value forthe `auto_reload` option, it will be determined automatically based on the`debug` value.
-
`strict_variables`*boolean*
If set to `false`, Twig will silently ignore invalidvariables (variables and or attributes/methods that do not exist) andreplace them with a `null` value. When set to `true`, Twig throws anexception instead (default to `false`).
-
`autoescape`*string|boolean*
If set to `true`, HTML auto-escaping will be enabled bydefault 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`,`html_attr`, or a PHP callback that takes the template "filename" and mustreturn the escaping strategy to use -- the callback cannot be a function nameto avoid collision with built-in escaping strategies).
As of Twig 1.17, the `filename` escaping strategy determines the escapingstrategy to use for a template based on the template filename extension (thisstrategy does not incur any overhead at runtime as auto-escaping is done atcompilation time.)
-
`optimizations`*integer*
A flag that indicates which optimizations to apply(default to `-1` -- all optimizations are enabled; set it to `0` todisable).
### Loaders
Loaders are responsible for loading templates from a resource such as the filesystem.
### Compilation Cache
All template loaders can cache the compiled templates on the filesystem forfuture reuse. It speeds up Twig a lot as templates are only compiled once; andthe performance boost is even larger if you use a PHP accelerator such as APC.See the `cache` and `auto_reload` options of `Twig_Environment` abovefor more information.
### Built-in Loaders
Here is a list of the built-in loaders Twig provides:
#### `Twig_Loader_Filesystem`
New in version 1.10: The `prependPath()` and support for namespaces were added in Twig 1.10.
`Twig_Loader_Filesystem` loads templates from the file system. This loadercan find templates in folders on the file system and is the preferred way toload them:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>$loader = new Twig_Loader_Filesystem($templateDir);
</pre></div></td></tr></table>
It can also look for templates in an array of directories:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>$loader = new Twig_Loader_Filesystem(array($templateDir1, $templateDir2));
</pre></div></td></tr></table>
With such a configuration, Twig will first look for templates in`$templateDir1` and if they do not exist, it will fallback to look for themin the `$templateDir2`.
You can add or prepend paths via the `addPath()` and `prependPath()`methods:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2</pre></div></td><td class="code"><div class="highlight"><pre>$loader->addPath($templateDir3);
$loader->prependPath($templateDir4);
</pre></div></td></tr></table>
The filesystem loader also supports namespaced templates. This allows to groupyour 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, thesemethods act on the "main" namespace):
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>$loader->addPath($templateDir, 'admin');
</pre></div></td></tr></table>
Namespaced templates can be accessed via the special`@namespace_name/template_path` notation:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>$twig->render('@admin/index.html', array());
</pre></div></td></tr></table>
#### `Twig_Loader_Array`
`Twig_Loader_Array` loads a template from a PHP array. It's passed an arrayof strings bound to template names:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4
5
6</pre></div></td><td class="code"><div class="highlight"><pre>$loader = new Twig_Loader_Array(array(
'index.html' => 'Hello {{ name }}!',
));
$twig = new Twig_Environment($loader);
echo $twig->render('index.html', array('name' => 'Fabien'));
</pre></div></td></tr></table>
This loader is very useful for unit testing. It can also be used for smallprojects where storing all templates in a single PHP file might make sense.
Tip
When using the `Array` or `String` loaders with a cache mechanism, youshould 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 youdon't want to see your cache grows out of control, you need to take careof clearing the old cache file by yourself.
#### `Twig_Loader_Chain`
`Twig_Loader_Chain` delegates the loading of templates to other loaders:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1
2
3
4
5
6
7
8
9
10
11</pre></div></td><td class="code"><div class="highlight"><pre>$loader1 = new Twig_Loader_Array(array(
'base.html' => '{% block content %}{% endblock %}',
));
$loader2 = new Twig_Loader_Array(array(
'index.html' => '{% extends "base.html" %}{% block content %}Hello {{ name }}{% endblock %}',
'base.html' => 'Will never be loaded',
));
$loader = new Twig_Loader_Chain(array($loader1, $loader2));
$twig = new Twig_Environment($loader);
</pre></div></td></tr></table>
When looking for a template, Twig will try each loader in turn and it willreturn 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`.
`Twig_Loader_Chain` accepts any loader that implements`Twig_LoaderInterface`.
Note
You can also add loaders via the `addLoader()` method.
### Create your own Loader
All loaders implement the `Twig_LoaderInterface`:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28</pre></div></td><td class="code"><div class="highlight"><pre>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
*/
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);
}
</pre></div></td></tr></table>
The `isFresh()` method must return `true` if the current cached templateis still fresh, given the last modification time, or `false` otherwise.
Tip
As of Twig 1.11.0, you can also implement `Twig_ExistsLoaderInterface`to make your loader faster when used with the chain loader.
### Using Extensions
Twig extensions are packages that add new features to Twig. Using anextension is as simple as using the `addExtension()` method:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>$twig->addExtension(new Twig_Extension_Sandbox());
</pre></div></td></tr></table>
Twig comes bundled with the following extensions:
- *Twig_Extension_Core*: Defines all the core features of Twig.
- *Twig_Extension_Escaper*: Adds automatic output-escaping and the possibilityto escape/unescape blocks of code.
- *Twig_Extension_Sandbox*: Adds a sandbox mode to the default Twigenvironment, making it safe to evaluate untrusted code.
- *Twig_Extension_Profiler*: Enabled the built-in Twig profiler (as of Twig1.18).
- *Twig_Extension_Optimizer*: Optimizes the node tree before compilation.
The core, escaper, and optimizer extensions do not need to be added to theTwig environment, as they are registered by default.
### 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 ownextensions.
### Core Extension
The `core` extension defines all the core features of Twig:
- [*Tags*](#);
- [*Filters*](#);
- [*Functions*](#);
- [*Tests*](#).
### Escaper Extension
The `escaper` extension adds automatic output escaping to Twig. It defines atag, `autoescape`, and a filter, `raw`.
When creating the escaper extension, you can switch on or off the globaloutput escaping strategy:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2</pre></div></td><td class="code"><div class="highlight"><pre>$escaper = new Twig_Extension_Escaper('html');
$twig->addExtension($escaper);
</pre></div></td></tr></table>
If set to `html`, all variables in templates are escaped (using the `html`escaping strategy), except those using the `raw` filter:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>{{ article.to_html|raw }}
</pre></div></td></tr></table>
You can also change the escaping mode locally by using the `autoescape` tag(see the [*autoescape*](#) doc for the syntax used beforeTwig 1.8):
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4
5</pre></div></td><td class="code"><div class="highlight"><pre>{% autoescape 'html' %}
{{ var }}
{{ var|raw }} {# var won't be escaped #}
{{ var|escape }} {# var won't be double-escaped #}
{% endautoescape %}
</pre></div></td></tr></table>
Warning
The `autoescape` tag has no effect on included files.
The escaping rules are implemented as follows:
-
Literals (integers, booleans, arrays, ...) used in the template directly asvariables or filter arguments are never automatically escaped:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4</pre></div></td><td class="code"><div class="highlight"><pre>{{ "Twig<br />" }} {# won't be escaped #}
{% set text = "Twig<br />" %}
{{ text }} {# will be escaped #}
</pre></div></td></tr></table>
-
Expressions which the result is always a literal or a variable marked safeare never automatically escaped:
~~~
{{ 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:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>{{ var|upper }} {# is equivalent to {{ var|upper|escape }} #}
</pre></div></td></tr></table>
-
The raw filter should only be used at the end of the filter chain:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3</pre></div></td><td class="code"><div class="highlight"><pre>{{ var|raw|upper }} {# will be escaped #}
{{ var|upper|raw }} {# won't be escaped #}
</pre></div></td></tr></table>
-
Automatic escaping is not applied if the last filter in the chain is markedsafe for the current context (e.g. `html` or `js`). `escape` and`escape('html')` are marked safe for HTML, `escape('js')` is markedsafe for JavaScript, `raw` is marked safe for everything.
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4
5</pre></div></td><td class="code"><div class="highlight"><pre>{% 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 %}
</pre></div></td></tr></table>
Note
Note that autoescaping has some limitations as escaping is applied onexpressions after evaluation. For instance, when working withconcatenation, `{{ foo|raw ~ bar }}` won't give the expected result asescaping is applied on the result of the concatenation, not on theindividual variables (so, the `raw` filter won't have any effect here).
### Sandbox Extension
The `sandbox` extension can be used to evaluate untrusted code. Access tounsafe attributes and methods is prohibited. The sandbox security is managedby a policy instance. By default, Twig comes with one policy class:`Twig_Sandbox_SecurityPolicy`. This class allows you to white-list sometags, filters, properties, and methods:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1
2
3
4
5
6
7
8
9
10</pre></div></td><td class="code"><div class="highlight"><pre>$tags = array('if');
$filters = array('upper');
$methods = array(
'Article' => array('getTitle', 'getBody'),
);
$properties = array(
'Article' => array('title', 'body'),
);
$functions = array('range');
$policy = new Twig_Sandbox_SecurityPolicy($tags, $filters, $methods, $properties, $functions);
</pre></div></td></tr></table>
With the previous configuration, the security policy will only allow usage ofthe `if` tag, and the `upper` filter. Moreover, the templates will only beable to call the `getTitle()` and `getBody()` methods on `Article`objects, and the `title` and `body` public properties. Everything elsewon't be allowed and will generate a `Twig_Sandbox_SecurityError` exception.
The policy object is the first argument of the sandbox constructor:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2</pre></div></td><td class="code"><div class="highlight"><pre>$sandbox = new Twig_Extension_Sandbox($policy);
$twig->addExtension($sandbox);
</pre></div></td></tr></table>
By default, the sandbox mode is disabled and should be enabled when includinguntrusted template code by using the `sandbox` tag:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3</pre></div></td><td class="code"><div class="highlight"><pre>{% sandbox %}
{% include 'user.html' %}
{% endsandbox %}
</pre></div></td></tr></table>
You can sandbox all templates by passing `true` as the second argument ofthe extension constructor:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>$sandbox = new Twig_Extension_Sandbox($policy, true);
</pre></div></td></tr></table>
### Profiler Extension
New in version 1.18: The Profile extension was added in Twig 1.18.
The `profiler` extension enables a profiler for Twig templates; it shouldonly be used on your development machines as it adds some overhead:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4
5</pre></div></td><td class="code"><div class="highlight"><pre>$profile = new Twig_Profiler_Profile();
$twig->addExtension(new Twig_Extension_Profiler($profile));
$dumper = new Twig_Profiler_Dumper_Text();
echo $dumper->dump($profile);
</pre></div></td></tr></table>
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/) [https://blackfire.io/]compatible format:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2</pre></div></td><td class="code"><div class="highlight"><pre>$dumper = new Twig_Profiler_Dumper_Blackfire();
file_put_contents('/path/to/profile.prof', $dumper->dump($profile));
</pre></div></td></tr></table>
Upload the profile to visualize it (create a [free account](https://blackfire.io/signup) [https://blackfire.io/signup] first):
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>blackfire --slot=7 upload /path/to/profile.prof
</pre></div></td></tr></table>
### Optimizer Extension
The `optimizer` extension optimizes the node tree before compilation:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>$twig->addExtension(new Twig_Extension_Optimizer());
</pre></div></td></tr></table>
By default, all optimizations are turned on. You can select the ones you wantto enable by passing them to the constructor:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3</pre></div></td><td class="code"><div class="highlight"><pre>$optimizer = new Twig_Extension_Optimizer(Twig_NodeVisitor_Optimizer::OPTIMIZE_FOR);
$twig->addExtension($optimizer);
</pre></div></td></tr></table>
Twig supports the following optimizations:
- `Twig_NodeVisitor_Optimizer::OPTIMIZE_ALL`, enables all optimizations(this is the default value).
- `Twig_NodeVisitor_Optimizer::OPTIMIZE_NONE`, disables all optimizations.This reduces the compilation time, but it can increase the execution timeand the consumed memory.
- `Twig_NodeVisitor_Optimizer::OPTIMIZE_FOR`, optimizes the `for` tag byremoving the `loop` variable creation whenever possible.
- `Twig_NodeVisitor_Optimizer::OPTIMIZE_RAW_FILTER`, removes the `raw`filter whenever possible.
- `Twig_NodeVisitor_Optimizer::OPTIMIZE_VAR_ACCESS`, simplifies the creationand access of variables in the compiled templates whenever possible.
### Exceptions
Twig can throw exceptions:
- `Twig_Error`: The base exception for all errors.
- `Twig_Error_Syntax`: Thrown to tell the user that there is a problem withthe template syntax.
- `Twig_Error_Runtime`: Thrown when an error occurs at runtime (when a filterdoes not exist for instance).
- `Twig_Error_Loader`: Thrown when an error occurs during template loading.
- `Twig_Sandbox_SecurityError`: Thrown when an unallowed tag, filter, ormethod is called in a sandboxed template.
- Twig
- Introduction
- Installation
- Twig for Template Designers
- Twig for Developers
- Extending Twig
- Twig Internals
- Deprecated Features
- Recipes
- Coding Standards
- Tags
- autoescape
- block
- do
- embed
- extends
- filter
- flush
- for
- from
- if
- import
- include
- macro
- sandbox
- set
- spaceless
- use
- verbatim
- Filters
- abs
- batch
- capitalize
- convert_encoding
- date
- date_modify
- default
- escape
- first
- format
- join
- json_encode
- keys
- last
- length
- lower
- merge
- nl2br
- number_format
- raw
- replace
- reverse
- round
- slice
- sort
- split
- striptags
- title
- trim
- upper
- url_encode
- Functions
- attribute
- block
- constant
- cycle
- date
- dump
- include
- max
- min
- parent
- random
- range
- source
- template_from_string
- Tests
- constant
- defined
- divisible by
- empty
- even
- iterable
- null
- odd
- same as