score:3

Accepted answer

You can create your own custom Twig extension like that :

1- The Twig extension class :

class SlugifyExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('slugify', array($this, 'slugifyFilter')),
        );
    }

    public function slugifyFilter($string)
    {
      $string = preg_replace('~[^\pL\d]+~u', '-', $string);
      $string = iconv('utf-8', 'us-ascii//TRANSLIT', $string);
      $string = preg_replace('~[^-\w]+~', '', $string);
      $string = trim($string, '-');
      $string = preg_replace('~-+~', '-', $string);
      $string = strtolower($string);

      if (empty($string)) {
        return 'n-a';
      }

      return $string;

    }

    public function getName()
    {
        return 'slugify_extension';
    }
}

2- register your Twig extension :

services:
    app.slugify_extension:
        class: AppBundle\Twig\AppExtension
        public: false
        tags:
            - { name: twig.extension }

3- Then use it :

{{ product.brand.title|slugify }}

More infos here.


Related Query

More Query from same tag