How to implement a new template engine Twig in Magento 2 ?

Twig is a well known PHP template engine. It allows us to write more efficient code using a syntax which is pretty close to HTML. The biggest advantage of twig is, it forces us to separate business logic and presentation logic, so that our code is better, more efficient and easily maintained. As it is always recommended not to write business logic or call Magento classes directly in templates and this is where twig helps us to strictly follow this recommendation.

How I can install and use twig in Magento 2 ?

  1. Download twig module.

By default twig module is not available in 2 . You need to install in with the help of composer. Kindly download twig module with the help of following command from Magento root

 composer require twig/twig 

It will download the latest version of twig and place the module under vendor directory. If you want to download any specific version of twig you can use

composer require twig/twig:version
2. Create module to list twig as a template engine in Magento.

Before proceeding further kindly follow these 2 tutorials to get the basic Helloworld module ready and working where we will be using twig template.

Following files will be added/modified in this tutorial:
  • Amitshree/Helloworld/etc/di.xml
  • Amitshree/Helloworld/View/TemplateEngine/Twig.php
  • Amitshree/Helloworld/Controller/Index/Index.php
  • Amitshree/Helloworld/view/frontend/layout/helloworld_index_index.xml
  • Amitshree/Helloworld/view/frontend/templates/hello.twig

Once you have the Helloworld module ready and working following above tutorials, you have to add twig as a new template engine. Magneto 2 provides us facility to add a new template engine with the help of di.xml . Create file Amitshree/Helloworld/etc/di.xml with following code

<?xml version="1.0"?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\View\TemplateEngineFactory">
            <argument name="engines" xsi:type="array">
                <item name="twig" xsi:type="string">Amitshree\Helloworld\View\TemplateEngine\Twig</item>

Now create Amitshree/Helloworld/View/TemplateEngine/Twig.php with following code

<?php namespace Amitshree\Helloworld\View\TemplateEngine; use Magento\Framework\View\TemplateEngine\Php; use Magento\Framework\App\Filesystem\DirectoryList; class Twig extends Php { /** * @var \Twig_Environment */ protected $_twig; /** * Base Directory Path */ protected $_baseDir; /** * @var \Magento\Framework\App\Filesystem\DirectoryList */ protected $_directoryList; /** * Constructor */ public function __construct( DirectoryList $directoryList ) { $this->_directoryList = $directoryList;
        $this->_baseDir = $this->getBaseDir();
     * Initialize Twig 
    protected function loadTwig()
        $loader = new \Twig_Loader_Filesystem($this->_baseDir);
        $this->_twig = new \Twig_Environment($loader);
     * Get Base Directory Path
    public function getBaseDir()
        return $this->_directoryList->getPath(DirectoryList::ROOT)."/";
     * Render Template
    public function render(\Magento\Framework\View\Element\BlockInterface $block, $fileName, array $dictionary = [])
        $this->_currentBlock = $block; // set current block instance for further use
        $template = str_replace($this->_baseDir, '', $fileName); // get path of template file from magento root directory
        return $this->_twig->loadTemplate($template)->render($dictionary); // load twig template

Now update layout file Amitshree/Helloworld/view/frontend/layout/helloworld_index_index.xml as given below and use twig template file instead of phtml file.

<?xml version="1.0"?>
<page xmlns:xsi="" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <referenceContainer name="content">
        <block class="Amitshree\Helloworld\Block\Helloworld" name="helloworld" template="Amitshree_Helloworld::hello.twig"/>

And finally create twig file Amitshree/Helloworld/view/frontend/templates/hello.twig with following content

Hello there !

After all the above changes your basis setup to using twig in Magento 2 is done. Now run helloworld module at and you should see the output.

    Hello there !

Note: If you do not see the output kindly run php bin/magento setup:upgrade and php bin/magento cache:clean command and verify.

Now modify your controller file Amitshree/Helloworld/Controller/Index/Index.php as given below to define twig variables which will be used in twig template file.

<?php namespace Amitshree\Helloworld\Controller\Index; class Index extends \Magento\Framework\App\Action\Action { protected $resultPageFactory; public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Framework\View\Result\PageFactory $resultPageFactory ) { $this->resultPageFactory = $resultPageFactory;
    public function execute()
        $page = $this->resultPageFactory->create();
        $blockInstance = $page->getLayout()->getBlock('helloworld');
        $blockInstance->assign(array('name' => 'Amit'));
        return $page;

Now call twig variable in your twig template file hello.twig like below

{{ name }}

You should be able to see the output:


That’s all. Hopefully you got the idea of twig implementation in Magento 2. I see there is a lot of rework need to be done (rewrite controllers, layouts, etc) if you want to remove default phtml files from Magento 2 and use twig instead. Though if you are developing a new module you can easily use it.

Leave a Reply