Symfony: create a twig extension

1. created a file called TheExtension.php with the following content:

namespace Something\Core\Extension\Twig;
use Twig_Extension;
use Twig_Filter_Method;

class TheExtension extends Twig_Extension
  public function getFilters()
    return array(
        'cleanup' => new Twig_Filter_Method($this, 'cleanup')

  public function cleanup($txt){
    $txt = str_replace(array("ä", "ö", "ü", "Ä", "Ü", "Ö", "ß"), array("ae", "oe", "ue", "Ae", "Ue", "Oe", "ss"), $txt);
    $txt = mb_strtolower($txt);
    $txt = str_replace(" ", "_", $txt);
    $txt = preg_replace('/[^A-Za-z0-9_]/', '', $txt);
    $txt = preg_replace('/_{2,}/','_',$txt);
    return $txt;

  public function getName()
    return 'the_extension';

2. save it in your project, ie at src/Something/Core/Extension/Twig/TheExtension.php

3. add this to the config.yml:

      class: Something\Core\Extension\Twig\TheExtension
          - { name: twig.extension }

And that’s it! Use it as follows:

{{ testvar|cleanup }}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.