Back To Top

CREATE TWIG EXTENSION FOR DRUPAL 8

Drupal 8 introduce Twig templating. Twig is a great templating system using with Symfony2. It is a big revolution for Drupal site builder, but with twig you can not use php function like you use it with phptemplate used in Drupal 7.

If you want transorm your data wih twig you must create a twig extension.

In this exemple, we built an extension du display a Drupal block directly from a twig template :

{{ display_block('my_block_id') }}

To to it, you must create a custom Drupal module. You can use the Drupal console to easily create your module.

In your module folder, frist create a new class in in a src subfolder :

For exemple : src/MyTwigExtension.php

<?php
namespace Drupal\MyTwigModule;

/**
 * Class DefaultService.
 *
 * @package Drupal\MyTwigModule
 */
class MyTwigExtension extends \Twig_Extension {

  /**
   * {@inheritdoc}
   * This function must return the name of the extension. It must be unique.
   */
  public function getName() {
    return 'block_display';
  }

  /**
   * In this function we can declare the extension function
   */
  public function getFunctions() {
    return array(
      new \Twig_SimpleFunction('display_block', 
        array($this, 'display_block'),
        array('is_safe' => array('html')
      )),
  }

  /**
   * The php function to load a given block
   */
  public function display_block($block_id) {
    $block = \Drupal\block\Entity\Block::load($block_id);
    return \Drupal::entityManager()->getViewBuilder('block')->view($block);
  }

}

In a second time you must register your extension as service : 

Create a service configuration file 

# src/MyTwigModule.services.yml
services:
  MyTwigModule.twig.MyTwigExtension:
    class: Drupal\MyTwigModule\MyTwigExtension
    tags:
      - { name: twig.extension }

 

And you are done :-)

You can now enable your module and use your Twig extension.

 

En savoir plus