Create a custom Twig filter in Drupal 8

Need more accurate results? Got a big list to verify?

Click the banner below to go to our recommended premium email verification service, Email Checker.

email-validation

Advertise on Leopathu

twig

Twig can be extended in many ways; you can add extra tags, filters, tests, operators, global variables, and functions. You can even extend the parser itself with node visitors. In this blog,

I am going to show you how to create new custom twig filters in drupal. For example we are going to create a filter to remove numbers from string, will explain with hello_world module.

Create hello_world folder in modules/custom/ folder with the following files,

1. hello_world.info.yml // It would contains normal module .info.yml file values, Check here for more details

2. hello_world.services.yml // It would contain following lines,

services:
  hello_world.twig_extension:
    arguments: ['@renderer']
    class: Drupal\hello_world\TwigExtension\RemoveNumbers
    tags:
      - { name: twig.extension }

3. src/TwigExtension/RemoveNumbers.php It would contain followings in that,


namespace Drupal\hello_world\TwigExtension;


class RemoveNumbers extends \Twig_Extension {    

  /**
   * Generates a list of all Twig filters that this extension defines.
   */
  public function getFilters() {
    return [
      new \Twig_SimpleFilter('removenum', array($this, 'removeNumbers')),
    ];
  }

  /**
   * Gets a unique identifier for this Twig extension.
   */
  public function getName() {
    return 'hello_world.twig_extension';
  }

  /**
   * Replaces all numbers from the string.
   */
  public static function removeNumbers($string) {
    return preg_replace('#[0-9]*#', '', $string);
  }

}

Enable the hello_world module and clear the cache, then you could use the “ removenum “ filters in your twig file,


{{ twig-value-with-numbers | removenum }}

It would remove the all numbers from the string, enjoy with your custom filters !

Download the hello_world module here