Articles / Creating a twig extension

When creating your theme in Drupal 8 you can now use Twig templating. However to make use of php functions you must use twig extensions.

There is currently a very useful contrib module Twig tweak that comes packed with functions such as

  • drupal_menu
  • drupal_image
  • drupal_config
  • drupal_view

If you find yourself needing to create you own custom extension then it is really quick. Here is an example of how you can make a check for an element containing class

{% if element|has_class('views-exposed-form') %}
    // Do something
{% endif %}

Start by making a custom module twig_extension_has_class using Drupal console or manually. Then add a file

/src/Twig/Extension/HasClassExtension.php

<?php

namespace Drupal\twig_extension_has_class\Twig\Extension;

/**
 * Class HasClassExtension.
 *
 * @package Drupal\twig_extension_has_class\Twig\Extension
 */
class HasClassExtension extends \Twig_Extension {

  /**
   * {@inheritdoc}
   */
  public function getFilters() {
    return array(
      new \Twig_SimpleFilter('has_class', [$this, 'hasClass']),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return 'twig_extension_has_class';
  }

  /**
   * Check if an element has a class.
   *
   * @param array $element
   *   The content array.
   * @param string $className
   *   The class name to check.
   *
   * @return bool
   *   True or false depending on class name.
   */
  public function hasClass(array $element, $className) {
    if (!empty($className) && isset($element['#attributes']) && isset($element['#attributes']['class'])) {
      $exists = in_array($className, $element['#attributes']['class']);
      return $exists;
    }

    return FALSE;
  }

}

You must then register the filter as a service at the root of your module in a file called

twig_extension_has_class.services.yml  

services:
  twig_extension_has_class.twig.extension:
    class: Drupal\twig_extension_has_class\Twig\Extension\HasClassExtension
    tags:
      - { name: twig.extension }

 

Tags
Drupal 8 Twig