a Sensio Labs Product

The flexible, fast, and secure
template language for PHP

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

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',
));

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.

Before Twig 0.9.3, the cache option did not exist, and the cache directory was passed as a second argument of the loader.

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.

To load a template from this environment you just have to call the loadTemplate() method which then returns a Twig_Template instance:

$template = $twig->loadTemplate('index.html');

To render the template with some variables, call the render() method:

echo $template->render(array('the' => 'variables', 'go' => 'here'));

The display() method is a shortcut to output the template directly.

Environment Options

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

$twig = new Twig_Environment($loader, array('debug' => true));

The following options are available:

Before Twig 0.9.3, the cache and auto_reload options did not exist. They were passed as a second and third arguments of the filesystem loader respectively.

Loaders

This section describes the loaders as implemented in Twig version 0.9.4 and above.

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

Built-in Loaders

Here is a list of the built-in loaders Twig provides:

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.

Create your own Loader

All loaders implement the Twig_LoaderInterface:

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
   */
  public 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
   */
  public 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
   */
  public function isFresh($name, $time);
}

As an example, here is how the built-in Twig_Loader_String reads:

class Twig_Loader_String implements Twig_LoaderInterface
{
  public function getSource($name)
  {
    return $name;
  }
 
  public function getCacheKey($name)
  {
    return $name;
  }
 
  public function isFresh($name, $time)
  {
    return false;
  }
}

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

Using Extensions

Twig extensions are packages that adds new features to Twig. Using an extension is as simple as using the addExtension() method:

$twig->addExtension(new Twig_Extension_Escaper());

Twig comes bundled with four extensions:

Built-in Extensions

This section describes the features added by the built-in extensions.

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:

The core extension does not need to be added to the Twig environment, as it is registered by default.

Escaper Extension

The escaper extension adds automatic output escaping to Twig. It defines a new tag, autoescape, and a new filter, safe.

When creating the escaper extension, you can switch on or off the global output escaping strategy:

$escaper = new Twig_Extension_Escaper(true);
$twig->addExtension($escaper);

If set to true, all variables in templates are escaped, except those using the safe filter:

{{ article.to_html|safe }}

You can also change the escaping mode locally by using the autoescape tag:

{% autoescape on %}
  {% var %}
  {% var|safe %}     {# var won't be escaped #}
  {% var|escape %}   {# var won't be doubled-escaped #}
{% endautoescape %}

The autoescape tag has no effect on included files.

The escaping rules are implemented as follows (it describes the behavior of Twig 0.9.5 and above):

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

$tags = array('if');
$filters = array('upper');
$methods = array(
  'Article' => array('getTitle', 'getBody'),
);
$properties = array(
  'Article' => array('title', 'body),
);
$policy = new Twig_Sandbox_SecurityPolicy($tags, $filters, $methods, $properties);

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.

The policy object is the first argument of the sandbox constructor:

$sandbox = new Twig_Extension_Sandbox($policy);
$twig->addExtension($sandbox);

By default, the sandbox mode is disabled and should be enabled when including untrusted template code by using the sandbox tag:

{% sandbox %}
  {% include 'user.html' %}
{% endsandbox %}

You can sandbox all templates by passing true as the second argument of the extension constructor:

$sandbox = new Twig_Extension_Sandbox($policy, true);

I18n Extension

The i18n extension adds gettext support to Twig. It defines one tag, trans.

You need to register this extension before using the trans block:

$twig->addExtension(new Twig_Extension_I18n());

Note that you must configure the gettext extension before rendering any internationalized template. Here is a simple configuration example from the PHP documentation:

// Set language to French
putenv('LC_ALL=fr_FR');
setlocale(LC_ALL, 'fr_FR');
 
// Specify the location of the translation tables
bindtextdomain('myAppPhp', 'includes/locale');
bind_textdomain_codeset('myAppPhp', 'UTF-8');
 
// Choose domain
textdomain('myAppPhp');

The chapter "Twig for Web Designers" contains more information about how to use the trans block in your templates.

Exceptions

Twig can throw exceptions:

This website is powered by PHP and Twig. The Twig logo is © 2010 Sensio Labs

The Sensio Labs Network

Since 1998, Sensio Labs has been promoting the Open-Source software movement by providing quality web application development, training, consulting.
Sensio Labs also supports several large Open-Source projects.