a Sensio Labs Product

The flexible, fast, and secure
template engine for PHP

Questions & Feedback

License

Creative Commons License Twig documentation is licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License.

Introduction

This is the documentation for Twig, the flexible, fast, and secure template engine for PHP.

If you have any exposure to other text-based template languages, such as Smarty, Django, or Jinja, you should feel right at home with Twig. It's both designer and developer friendly by sticking to PHP's principles and adding functionality useful for templating environments.

The key-features are...

  • Fast: Twig compiles templates down to plain optimized PHP code. The overhead compared to regular PHP code was reduced to the very minimum.
  • Secure: Twig has a sandbox mode to evaluate untrusted template code. This allows Twig to be used as a template language for applications where users may modify the template design.
  • Flexible: Twig is powered by a flexible lexer and parser. This allows the developer to define its own custom tags and filters, and create its own DSL.

Prerequisites

Twig needs at least PHP 5.2.4 to run.

Installation

The recommended way to install Twig is via Composer:

1
composer require twig/twig:1.*

Note

To learn more about the other installation methods, read the installation chapter; it also explains how to install the Twig C extension.

Basic API Usage

This section gives you a brief introduction to the PHP API for Twig.

1
2
3
4
5
6
require_once '/path/to/vendor/autoload.php';

$loader = new Twig_Loader_String();
$twig = new Twig_Environment($loader);

echo $twig->render('Hello {{ name }}!', array('name' => 'Fabien'));

Twig uses a loader (Twig_Loader_String) to locate templates, and an environment (Twig_Environment) to store the configuration.

The render() method loads the template passed as a first argument and renders it with the variables passed as a second argument.

As templates are generally stored on the filesystem, Twig also comes with a filesystem loader:

1
2
3
4
5
6
$loader = new Twig_Loader_Filesystem('/path/to/templates');
$twig = new Twig_Environment($loader, array(
    'cache' => '/path/to/compilation_cache',
));

echo $twig->render('index.html', array('name' => 'Fabien'));

Tip

If you are not using Composer, use the Twig built-in autoloader:

1
2
require_once '/path/to/lib/Twig/Autoloader.php';
Twig_Autoloader::register();
This website is powered by PHP and Twig. The Twig logo is © 2010-2012 Sensio Labs