3

I want to slugify a value, for example "slugName = Spain & Italy"

When I make my slug in TWIG {{ slugName|slugify }}, the result is Spain_amp_Italy

Is it possible to set a REGEX in Twig, so that my "&" for example will be translated in "and" ? THANKS

Zwen2012
  • 3,360
  • 9
  • 40
  • 67
  • Consider making your own twig filter: http://symfony.com/doc/current/cookbook/templating/twig_extension.html It's a useful skill to master and will let your slugify exactly how you want. Hint: Take a look at twig's slugify source code. – Cerad Apr 16 '15 at 15:15

2 Answers2

5

You could concatenate multiple filters, and use a simple function replace():

{{ slugName| replace({'&': 'and'}) | slugify }}
Alessandro Lai
  • 2,254
  • 2
  • 24
  • 32
2

You can create a custom function to do this

<?php
$twig->addFilter(new Twig_Filter('ampersand_to_and', function( $string = '' ) {

    return preg_replace('/(&amp;|&)/m', 'and', $string );
}));

and then you can use it as follows:

<p>{{ 'Spain & Italy'|ampersand_to_and }}</p>
<p>{{ 'Spain &amp; Italy'|ampersand_to_and }}</p>
Craig Wayne
  • 4,499
  • 4
  • 35
  • 50