Drupal 8 has seen a massive turnaround when it comes to templating, unlike the previous version of drupal such as Drupal 7 instead of having a PHP Template, Drupal 8 has Twig which is created by SensioLabs, the same people who develop the Symfony2 framework and used to overhaul Drupal 8’s codebase. The game changer of this feature is that instead of calling the regular PHP functions, twig enable you to call and create filters which can be extended in many ways such as tags, filters, operators, global variables, and functions. Even though there’s a numerous function that can be used in twig, we can create and customize our own filter which makes it more flexible and easier to use and 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. Here is a sample snippet needed to create one:

This example assumes you have a module called:

custom_twig_filter1.png

Basic definition of the in service.

custom_twig_filter2.png

The key tags are 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.

custom_twig_filter3.png

After that just run “drush cr” or clear you cache and you can use the custom filter in your templates.

custom_twig_filter4.png

This sample will return “2”. Easy as pie! So start exploring and create more twig function and enjoy!

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.