How to write custom Twig filter in Drupal 8

By yuseferi, 9 January, 2014
Twig Filter in Drupal 8

Twig is one of the  good template engines which is provided by SensioLabs, It’s syntax originates from Jinja and Django template, it’s Secure, Flexible and Fast : 

Twig is a modern template engine for PHP

• Fast: Twig compiles templates down to plain optimized PHP code. The overhead compared to regular PHP code was reduced to the very minimum.

• Secure: Twig has a sandbox mode to evaluate untrusted template code. This allows Twig to be used as a template language for applications where users may modify the template design.

• Flexible: Twig is powered by a flexible lexer and parser. This allows the developer to define its own custom tags and filters, and create its own DSL.


I’m not going to write about twig itself in this Article and it might I’ll do in future but in this article, I’m going to write a custom twig extension.


It was a good news that  Drupal 8 want to  use some of  Symfony’s useful components  in its core, one of them is using Twig template Engine instead of Php template engine which faced a lot of Drupal Front-end Developers with  hard situation which let them do everything in template engine even DROP the Database completely!!!, but with using Twig template Engine we don’t let PHP codes work on template files, but on of the big disadvantages of this is restrict Front-End developer to use a limited number of filters and functions in template.


The solution is Extend the Twig Extensions easily, I’m going to write a custom filter to show how is it simple, let’s go.


1. Create A custom Module ( or you can do it in your exists custom modules) :


 in `/modules/` create a directory, call it ctwigfilters, then create with following contain

name: Custom Twig Filters
type: module
description: 'Provide some custom twig filter and functions(later)'
package: Core
core: '8.x'


Create // It would contain following lines,

    arguments: ['@renderer']
    class: Drupal\ctwigfilters\TwigExtension\MyHumanize
      - { name: twig.extension }

3.Create MyHumanize.php   at ctwigfilters/src/TwigExtension/ It would contain followings in that,

 * Created by PhpStorm.
 * User: Zhilevan
 * Date: 1/9/18
 * Time: 23:38

namespace Drupal\ctwigfilters\TwigExtention;

class MyHumanize extends \Twig_Extension {
    public function getFilters()
        return [ new \Twig_SimpleFilter('myhumanize', array($this, 'myHumanize'))];

    public function getName()
        return 'ctwigfilters.twig_extension';

    public static function myHumanize($string)
        $str = trim(strtolower($str));
        $str = preg_replace('/[^a-z0-9\s+]/', '', $str);
        $str = preg_replace('/\s+/', ' ', $str);
        $str = explode(' ', $str);
        $str = array_map('ucwords', $str);
        return implode(' ', $str);

Enable the Custom Twig Filters module and clear the cache, then you could use the “myhumanize” filters in your twig file,


{{ your-variable | myhumanize }}


Done, Yup, very simple, isn’t?


The source files of this Article is available on my GitHub at this URL


Additional resource List of Twig Filter and Functions