Overview of Twig Extentions in Drupal 8

28 / Feb / 2017 by Ashish Pandey 1 comments

Drupal 8 introduces a great templating system “Twig which is originating from Symfony, a PHP framework.

This has brought about a big change in the Drupal community. Unlike Drupal 7, developers can’t use PHP functions directly now on. Twig is a template framework and is a direct replacement for PHP template.

Twig extension provides more flexibility to process almost anything inside twig. Twig extends in many ways such as tags, filters, operators, global variables, and functions.

Outlined below are the advantages of using Twig Extensions:

Drupal 8 views can increase the challenge in the case where you want to change, update or modify a value or need to process the content in the field. When you need to write a code often, try to reuse it rather than writing it from scratch every time.

Benefits of Twig Extensions:

Creating twig extension helps to separate the compiled code and the code at runtime execution. Twig extension improves the experience with efficient coding techniques that involve lesser efforts and high flexibility.

In the below example, we built an extension to render an image alt tag inside twig templates.

To get started, we need to create a module for TwigExtension.

Creating your Twig Extension

To start with it first, we need to create a module.

1.) Create a new module inside: /modules/custom/ directory inside your drupal project.

2.) Our new module structure would look like this:


3.) demo_module.info.yml contains

name: demo_module
type: module
description: ‘Provides Twig Extension that process the Alt tag of any given image.’
core: 8.x
version: 0.1.1

Information provided inside module_name.info.yml is used to be displayed on admin module page.

4.) Create a service file inside your module as ‘module_name.services.yml’

    class: Drupal\demo_module\TwigExtension
      - {name: twig.extension}

5.) The TwigExtension.php contains the following code

namespace Drupal\demo_module;
use Drupal\block\Entity\Block;
use Drupal\user\Entity\User;
use Drupal\node\Entity\Node;

 * Class DefaultService.
 * @package Drupal\demo_module
class TwigExtension 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('getImageAlt', array($this, 'getImageAlt'), array('is_safe' => array('html'))),
   * This function is used to return alt of an image
   * Set image title as alt.
  public function getImageAlt($item) {
    $image_alt = NULL;
    if (method_exists($item, 'getEntity')) {
      $entity = $item->getEntity();
      $slide_image = $entity->get('field_image')->getValue();
      if ($slide_image) {
        if (isset($slide_image[0])) {
          $image = $slide_image[0];
          // set "item title" as alt.
          $item_value = $entity->get('field_item_title')->getValue();
          $image_alt = trim(strip_tags($item_value[0]['value']));
            return $image_alt;
          else {
            $image_alt = $image['alt'];
            return $image_alt;
    return $image_alt;

6.) Now, enable your demo_module module.
drush en demo_module -y

7.) Clear the cache.
drush cr

8.) Applying Twig Extension to your twig template
You can make a call to your TwigExtension directly inside template using “{{ }}” braces. These braces are used to render any content placed inside them.

{% set imageAlt = getImageAlt(the_image) %}
<img class="slide-content" src="{{ image_style_url[key] }}" alt="{{ imageAlt }}" title="{{ the_image.title }}">

Moving further, set the value from getImageAlt() function to a variable imageAlt inside node.html.twig placed in themes/my_theme/templates directory and then, render the variable imageAlt inside image alt tag.

TwigExtension provides a great accessibility to the code which is often reused. With easy reusability of the code, it also saves a lot of time and efforts. Hope you will now be able to use Twig in Drupal 8.

Watch out my blog for more updates on Drupal 8.


comments (1 “Overview of Twig Extentions in Drupal 8”)

  1. Abhinav Mukund

    Tutorial is destructive, not proivide enough info. like –
    1. the_image variable is unknown.
    2. Not clear description of this function.

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


Leave a comment - Abhinav Mukund Cancel reply