Reading list Switch to dark mode

    How To Add And Use Twig Template Engine in Magento2

    Updated 16 February 2023

    Here we will see how to implement twig template engine in magento2.
    As you already know Magento2 uses many new features and technologies. There is a feature in Magento2 by which we can use additional template engine for templating purpose.
    In this article we will learn how we can implement twig with magento2.
    Twig is a template engine which is very fast, secure and flexible.
    For more details about twig template click here.

    Twig Template Engine in Magento2

    Follow these three steps to include twig template engine in magento2.

    • Include twig package
    • Set template engine in di.xml
    • Include twig package

    Step 1- Include twig package

    First of all you have to include twig package in magento2. To include twig package edit compose.json file and add line “twig/twig”: “~1.28.2” in require section

    "require": {
        "twig/twig": "~1.28.2"
    }

    After this run composer:update command from terminal. Now twig package is included in your magento.
    You can check it in vendor folder. You will see a twig folder there.
    1.28.2 is the version of twig package.

    Step 2- Set template engine in di.xml

    After including twig package now its time to configure magento.

    Searching for an experienced
    Magento 2 Company ?
    Find out More
    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
        <type name="Magento\Framework\View\TemplateEngineFactory">
            <arguments>
                <argument name="engines" xsi:type="array">
                    <item name="twig" xsi:type="string">Webkul\Twig\View\TemplateEngine\Twig</item>
                </argument>
            </arguments>
        </type>
    </config>
    

    Step 3- Configure twig template file

    Create Twig.php class as you defined it in di.xml file and extend it by class \Magento\Framework\View\TemplateEngine\Php

    <?php
    namespace Webkul\Twig\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();
            $this->loadTwig();
        }
    
        /**
         * Initialize Twig 
         */
        protected function loadTwig()
        {
            \Twig_Autoloader::register();
            $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
        }
    }

    Note:  If in case you are using Twig version 3.x. , then configure the twig template file as mentioned below.

    <?php
    namespace Webkul\Twig\View\TemplateEngine;
    
    use Magento\Framework\View\TemplateEngine\Php;
    use Magento\Framework\App\Filesystem\DirectoryList;
    
    class Twig extends Php
    {
        public const PATH_TO_TEMP = "app/code/Webkul/Twig/view/frontend/templates/";
        /**
         * @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();
            $this->loadTwig();
        }
    
        /**
         * Initialize Twig 
         */
        protected function loadTwig()
        {
            $dir = $this->_baseDir.self::PATH_TO_TEMP;
            $loader = new \Twig\Loader\FilesystemLoader($dir);
            $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
            $pathToTemp = $this->_baseDir.self::PATH_TO_TEMP;
            $fileName = trim(str_replace($pathToTemp, "", $fileName));
            return $this->_twig->render($fileName,$dictionary); // render twig template
        }
    }

    Everything is ready now. You can use twig extension files for templating.
    Here is an example. I just called a twig template file on home page.

    <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceContainer name="content">
                <block class="Magento\Framework\View\Element\Template" name="test.twig" template="Webkul_Twig::sample.twig"/>
            </referenceContainer>
        </body>
    </page>
    

    And the output of this snippet will be same as the screenshot.
    Twig Template
    That’s all for twig template engine in magento2.
    If you have any issue or query, comment below.

    . . .

    Leave a Comment

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


    1 comments

  • Amit Kumar Thakur
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home