twig Getting started with twig Basic API Usage


It can also be installed by downloading the source code and placing it in a directory of your project. However there are many benefits to using composer.

require '/path/to/lib/Twig/Autoloader.php';

$loader = new Twig_Loader_Filesystem('/path/to/templates');

$options = array(
    'strict_variables' => false,
    'debug' => false,
    'cache'=> false

$twig = new Twig_Environment($loader, $options);

When creating a new Twig_Environment instance, you can pass an array of options as the constructor's second argument. Here is a list of the available options:

  • debug (boolean, default false)

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

  • charset (string, default utf-8)

The charset used by the templates.

  • base_template_class (string, default Twig_Template)

The base template class to use for generated templates.

  • cache (string or false, default false)

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

  • auto_reload (boolean, default inherited from debug)

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_variables (boolean, default false)

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.

  • autoescape (string or boolean, defaulttrue)

If set to true, HTML auto-escaping will be enabled by default for all templates.

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 must return the escaping strategy to use -- the callback cannot be a function name to avoid collision with built-in escaping strategies).

As of Twig 1.17, the filename 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.)

  • optimizations (integer, default -1)

A flag that indicates which optimizations to apply:
set to -1 to enabled all optimalizations
set o 0 to disable all optimalitazations

Official Twig Installation Guide

A Twig PHP extension (written in C) can also be compiled and installed, and the PHP package will automatically take advantage of that for optimizing some common routines.