Create a custom Twig filter in Drupal 8

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

1. 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 }

2. 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('website', array($this, 'removeSpecialCharcter')),
    ];
  }

  /**
   * 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 removeSpecialCharcter($string) {
   // write your code logic
    return preg_replace('#[0-9]*#', '', $string);
  }

}

Enable the hello_world module and clear the cache, then you could use the “website“ filters in your twig file. ‘Clear all Cache’ from this url: yourdomain.com/admin/config/development/performance
{{ twig-value | website }}

Leave a Reply

Your email address will not be published. Required fields are marked *