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...
Twig needs at least PHP 5.2.4 to run.
You have multiple ways to install Twig.
1 | curl -s http://getcomposer.org/installer | php
|
composer.json file in your project root:1 2 3 4 5 | {
"require": {
"twig/twig": "1.*"
}
}
|
1 | php composer.phar install
|
Note
If you want to learn more about Composer, the composer.json file syntax
and its usage, you can read the online documentation.
git clone git://github.com/fabpot/Twig.gitpear channel-discover pear.twig-project.orgpear install twig/Twig (or pear install twig/Twig-beta)New in version 1.4: The C extension was added in Twig 1.4.
Twig comes with a C extension that enhances the performance of the Twig runtime engine. You can install it like any other PHP extension:
1 2 3 4 5 | $ cd ext/twig
$ phpize
$ ./configure
$ make
$ make install
|
Finally, enable the extension in your php.ini configuration file:
1 | extension=twig.so
|
And from now on, Twig will automatically compile your templates to take
advantage of the C extension. Note that this extension does not replace the
PHP code but only provides an optimized version of the
Twig_Template::getAttribute() method.
Tip
On Windows, you can also simply download and install a pre-built DLL.
This section gives you a brief introduction to the PHP API for Twig.
The first step to use Twig is to register its autoloader:
1 2 | require_once '/path/to/lib/Twig/Autoloader.php';
Twig_Autoloader::register();
|
Replace the /path/to/lib/ path with the path you used for Twig
installation.
If you have installed Twig via Composer you can take advantage of Composer's autoload mechanism by replacing the previous snippet for:
1 | require_once '/path/to/vendor/autoload.php'
|
Note
Twig follows the PEAR convention names for its classes, which means you can easily integrate Twig classes loading in your own autoloader.
1 2 3 4 | $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'));
|