lookingGlass
lookingGlass

Reputation: 365

Use twig to filter variable into url

I have a variable {{ name }} which outputs Treatment & Support. I need to remove the & symbol and convert the name into a useable url slug with twig for example: treatment-support.

I have having trouble finding the correct twig fitlers. I am looking at I am looking at http://twig.sensiolabs.org/documentation. So far all I have is

{{ name |lower }}

To reiterate I need to use twig to turn Treatment & Support into treatment-support using the {{ name }} variable.

Any help is appreciated.

Upvotes: 0

Views: 2709

Answers (3)

Craig Wayne
Craig Wayne

Reputation: 5068

You could create a custom filter or use the suggestion from @alexf

however in the event of multiple instances of this, i would suggest using a custom filter

something like...

<?php
$loader = new Twig_Loader_Filesystem();
$twig = new Twig_Environment($loader);

/**
 * Creates slugs from strings
 */
$twig->addFilter(new Twig_Filter('slugify', function( $string = '' ) {

    if( !$string ){
        return $string;
    }

    if( !is_string( $string ) ){
        throw new Exception('Only strings can be slugified.' );
    }

    //lowercase the whole string
    $slug = strtolower($string);

    //create an array of all the words/characters
    $slug_array = explode( ' ', $slug );

    //replace all special characters with empty strings
    array_walk( $slug_array, function( &$item, $key ){
        $item = preg_replace('/[^a-z0-9]/', '', $item );
        return $item;
    });

    //remove empty items from the array
    $slug_array = array_filter( $slug_array );

    //reconstruct the string
    $slug = join( '-', $slug_array );
    return $slug;
}));

Then you can use it like so

<p>{{ 'Treatment & Support'|slugify }}</p>
<p>{{ 'Heres a sentence with 2 numbers 8o'|slugify }}</p>
<p>{{ 'Hello World!'|slugify }}</p>

And that will produce the following output

treatment-support 
heres-a-sentence-with-2-numbers-8o 
hello-world

Upvotes: 0

Monal Soft
Monal Soft

Reputation: 320

you can create your own filters in drupal8 for twig.

follow this:

http://leopathu.in/content/create-custom-twig-filter-drupal-8

if didn't work please comment. I have successfully created some filters for my drupal website.

Upvotes: 0

alexf
alexf

Reputation: 1301

You can use twig replace filter :

{{ name|replace({' & ': '-', '&amp;': '-'}) }}

As @DarkBee said in comment, for something more complex, you can use Slugify

Upvotes: 3

Related Questions