Using Twig with Phalcon PHP

You might wonder why using Twig with Phalcon PHP and not using Volt. Well, i had 2 main reasons:

1. I have been using Twig for the last 2 years and it’s available as a C extension also.
2. Using Volt it’s almost exactly the same thing, but for now it seems that Volt is not so stable – mostly because of the view renderer. I had a lot of problems while trying to render Volt templates (Phalcon 1.3.0). Anyway, when it will be stable, i will use Volt for sure. So, if you read this while you have a stable Volt and it is not mandatory to use Twig, just use Volt.

Using Twig with Phalcon PHP

Here is what you have to do:

1. Download Twig
2. Register it in your bootstrap

require "YOUR_PATH_TO_TWIG/Autoloader.php";

3. Download Twig View from Incubator and register it to your namespace.

4. Edit your service file and add a twig service to DI

$di['twigService'] = function($view, $di) {
        'debug'               => true,
        'charset'             => 'UTF-8',
        'base_template_class' => 'Twig_Template',
        'strict_variables'    => false,
        'autoescape'          => false,
        'cache'               => __DIR__.'/../../cache/twig/',
        'auto_reload'         => null,
        'optimizations'       => -1,

    $twig = new View($view, $di);
    return $twig;

4. Enable Twig as your view engine:

$di['view'] = function() {
    $view = new \Phalcon\Mvc\View();
    $view->setViewsDir(__DIR__ . '/../views/');
            ".twig" => 'twigService'
    return $view;

That’s it. Create a new file with the extenstion .twig in your view folder, and everything should run as expected.