Symfony: create a twig extension


December 19, 2013 at 11:49
Symfony

1. created a file called TheExtension.php with the following content:
<?php
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:
services: 
    core.twig.the_extension:
      class: Something\Core\Extension\Twig\TheExtension
      tags:
          - { name: twig.extension }
And that's it! Use it as follows:
{{ testvar|cleanup }}

Tags: Extension symfony Twig


Hinterlasse einen Kommentar:
Search