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.

2 Replies to “Using Twig with Phalcon PHP”

  1. Hi Calin Rada!
    Thak you for your information about integrating twig into phalcon. But I’ve got some trouble and I’ve tryed but unlikely couldn’t solve them on my own.
    I think there is a problem with Twig classes autoloading.

    I’ve moved downloaded twig to folder \app\twig\ and put Twig.php from phalcon/incubator rigt into it.
    The \public\index.php now starts with
    require “../app/twig/Autoloader.php”;
    require “../app/twig/Twig.php”; // without this line: Class ‘Phalcon\Mvc\View\Engine\Twig’ not found

    I think that’s the point, but I don’t understand where exactly.
    “3. Download Twig View from Incubator and register it to your namespace.”
    What should I put into resister prefix argument to prevent this?
    Fatal error: Class ‘Phalcon\Mvc\View\Engine\Twig\Environment’ not found in \home\phalcon\www\app\twig\Twig.php on line 28

    Soryy for mistakes. English isn’t my native language.
    Thank you in advance!

    1. Hi Alexey,

      Please be sure that you didn’t overwrite the default Twig.php file. There are 2 files: one is the view found in the twig repo and the otherone in the Phalcon’s incubator. This are completley different files.

Leave a Reply

Your email address will not be published. Required fields are marked *