How to create custom twig filters in Symfony 4

5 May 2019

Symfony 4 Twig

Creating your own custom twig filters is easely done. All we need to do is to create new a Class Extension. Let's say we're having blog and want to display a preview of our blog posts on the startpage. For that reason we need a truncate filter reducing the words of our main content.

Creating the Truncate Filter

Create the file truncateFilter under src/Twig/TruncateFilter.php

If we are using the default configuration of Symfony 4, we don't have to do anything more. Symfony 4 uses any class inside src/ as a service.

Using the Truncate Filter

We can now use your custom filter as we would normally do. Per default the filter will reduce the number of words to 50. But the default behavoir can be overwritten with the optional parameter.

Takeaway

Twig has already a lot of build in filters and functions. Also Symfony 4 provides some extra filters and function for the twig extension. So check them before you write your own filters - a solution for your need might already exist

Symfony 4 Twig