Extending Twig functions and filters
Last Updated: 23 May 2025
Summary
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 files:
custom_twig.info.yml:
name: 'Custom Twig'
type: module
description: 'Provides custom Twig filters and functions.'
core_version_requirement: ^8 || ^9 || ^10
package: Custom
Step 2: Create a Twig Extension Class
Inside your module, create a TwigExtension.php
file in the src/Twig
directory:
custom_twig/src/Twig/TwigExtension.php
<?php
namespace Drupal\custom_twig\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
class TwigExtension extends AbstractExtension {
public function getFilters() {
return [
new TwigFilter('reverse', [$this, 'reverseString']),
];
}
public function getFunctions() {
return [
new TwigFunction('greet', [$this, 'greetUser']),
];
}
public function reverseString($string) {
return strrev($string);
}
public function greetUser($name = 'Guest') {
return 'Hello, ' . $name . '!';
}
}
Step 3: Register the Extension as a Service
Now tell Drupal to load your Twig extension by declaring it in a services.yml
file.
custom_twig.services.yml
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. If you need help implementing or extending Twig logic in your Drupal site, feel free to reach out via our Contact Us page — we’re happy to help!