Search code examples
symfonytwig

Twig replace plus and two spaces in string


I have a string like this:

Some + Name 

I want that changed to

some-name

I'm using the replace filter which works nicely. However I need to replace a whole lot more characters (for use in urls) which conflict with the above string.

{{ product.brand.title | replace({' ' : '-', '/&' : '-', "'" : "", '+':'', '.':''}) | lower | raw }}

When using the above replace function with the mentioned string I get

Some--Name

What would be the best way to accomplish the desired string?? With in mind I need to change most characters into dashes. I tried escape as well but that didn't work properly. Think of:

Dr. Brown's -> dr-browns
Burt's Bees -> burts-bees
naïf care -> naif-care

Solution

  • 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.