Extending Twig functions and filters
Enhance your Drupal themes by adding custom Twig filters and functions. This guide shows how to extend Twig in a Drupal-friendly way using your own module and PHP classes.
Introduction
Twig is a powerful templating engine, used to output dynamic content safely and elegantly. While Drupal provides many Twig filters and functions out of the box, you might encounter situations where the built-in options are not enough. In such cases, you can create custom filters and functions that are reusable and tailored to your needs.
In this tutorial, you’ll learn how to define custom Twig extensions inside a custom module.
Step 1: Set Up a Custom Module
If you don’t already have a custom module, create one. For example:
- Module name:
custom_twig - Create the following file:
1name: 'Custom Twig'
2type: module
3description: 'Provides custom Twig filters and functions.'
4core_version_requirement: ^8 || ^9 || ^10
5package: CustomStep 2: Create a Twig Extension Class
Inside your module, create a TwigExtension.php file in the src/Twig directory:
1<?php
2
3namespace Drupal\custom_twig\Twig;
4
5use Twig\Extension\AbstractExtension;
6use Twig\TwigFilter;
7use Twig\TwigFunction;
8
9class TwigExtension extends AbstractExtension {
10
11 public function getFilters() {
12 return [
13 new TwigFilter('reverse', [$this, 'reverseString']),
14 ];
15 }
16
17 public function getFunctions() {
18 return [
19 new TwigFunction('greet', [$this, 'greetUser']),
20 ];
21 }
22
23 public function reverseString($string) {
24 return strrev($string);
25 }
26
27 public function greetUser($name = 'Guest') {
28 return 'Hello, ' . $name . '!';
29 }
30}Step 3: Register the Extension as a Service
Now tell Drupal to load your Twig extension by declaring it in a services.yml file.
1services:
2 custom_twig.twig_extension:
3 class: Drupal\custom_twig\Twig\TwigExtension
4 tags:
5 - { name: twig.extension }Make sure this file is placed at the root of your module.
Step 4: Use Your Custom Filters and Functions in Twig
Once everything is set up and cache is cleared, you can use your custom logic directly in your Twig templates.
Example:
1{{ 'Drupal'|reverse }} {# Outputs: lapurD #}
2{{ greet('Alice') }} {# Outputs: Hello, Alice! #}Conclusion
Custom Twig extensions in Drupal allow you to move complex logic out of templates and into reusable PHP functions. This keeps your templates clean, readable, and maintainable. Once your module is enabled, these filters and functions can be used across all your themes and templates.