1st November 2020 - 7 minutes read time
Whilst Twig is a powerful tool in its own right there are occasions when you need to pull out data from Drupal or manipulate it in certain ways. I normally do this using preprocess steps, but I recently found that it was also possible to extend Twig within the Drupal framework to provide your own functions and filters. This can be useful if you have custom templates and need to perform special actions on data items to format them in different ways.
Setting Up
Before we can create Twig filters and functions in Drupal we need to tell Drupal that we have a class that contains them. This is done by creating an entry in the your module services file that contains the tag tag.extension. In a module called "custom_twig" the file would be called custom_twig.services.yml and would contain the following.