Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Creating your own Twig Extension in Drupal

Parent Feed: 

The templating engine of Drupal 8 has seen a massive turnaround. Unlike Drupal 7, there’s Twig in Drupal 8 instead of PHPTemplate. Twig is basically a templating language for PHP i.e a tool used to output variables inside HTML. Fabien Potencier, the creator of the Symfony framework, gave life to Twig. Contrary to Drupal 7, you cannot call the regular PHP functions in your templates in Drupal 8. The way forward, in Drupal 8, is to create filters and functions.

Icon resembling human wearing blue shirt standing in front of a white board explaining Twig Extension in Symfony and Drupal


Twig extension gives more flexibility to process nearly anything inside the twig. Twig can be extended in many ways such as tags, filters, operators, global variables, and functions.

One of the major plus points of creating a twig extension in Drupal 8 is in the view.

Drupal 8 views can often be more challenging in the case where you want to perform operations on the value or need to process the content in the field. When you need to write code often, try to reuse it rather than writing it from scratch every time.

You must use a filter when you want to transform the data you want to display. Imagine you have a title that you always want to be capitalized. For example, twig has the capitalize filter that allows you to transform any text into its equivalent in uppercase.

I came across Twig Extension during one of my E-commerce projects where I had to print dynamic currency name. Drupal Commerce allows only 3 characters long currency code and they have also implemented their own Twig Extension to convert Price object into equivalent price format. So to handle this case where I have to show currency name with more number of characters, I had implemented my own Twig Extension. Similarly, there are several other cases where these Twig Extension can be very handful.

Let’s see an example where we will create a filter that will allow us to count the number of words in the article. The process of creating filters and functions is exactly the same as normal Twig. Also, you can use word count to display the reading time of the article or any other use case as per the requirement.

The main difference between regular Twig and Drupal 8 Twig is that, in Drupal 8, you must create a service definition of the class you are creating and the class must also belong to a namespace, otherwise it will not be registered as a Twig filter in the Drupal environment.

This example assumes you have a module called:

twig_word_count_extension


This will be the basic definition of the inn service.

twig_word_count_extension.services.yml
services:
  twig_word_count_extension.twig_extension:
    class: Drupal\twig_word_count_extension\TwigExtension\TwigWordCountExtension
    tags:
      - { name: twig.extension }


The key tags are also absolutely necessary and that is what Drupal tells you what this class is supposed to do (that is, register it as an extension of Twig).

And now the source code that should be placed in the path defined in the class service definition key.

<?php

namespace Drupal\twig_word_count_extension\TwigExtension;

use Twig_Extension;
use Twig_SimpleFilter;

class TwigWordCountExtension extends \Twig_Extension  {
  /**
   * This is the same name we used on the services.yml file
   */
  public function getName() {
    return 'twig_word_count_extension.twig_extension';
  }

  // Basic definition of the filter. You can have multiple filters of course.
  public function getFilters() {
    return [
      new Twig_SimpleFilter('word_count', [$this, 'wordCountFilter']),
    ];
  }
  // The actual implementation of the filter.
  public function wordCountFilter($context) {
    if(is_string($context)) {
      $context = str_word_count($context);
    }
    return $context;
  }
}


Clear your caches and now, if everything goes according to plan, you can use the filter in your templates.

{{ "shuffle me!" | word_count }} {# Return 2. #}


Note: If these twig extensions don’t have other service dependencies (i.e. if you don't inject services in them), the performance is not affected. However, if these extensions have lots of complex dependencies, for example, say those making database connections or perform heavy operations, the performance loss can be significant.

To avail help from our experts for your Drupal projects, you can check out our suite of services. You can also talk to us at [email protected].

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web