Take the 2-minute tour ×
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It's 100% free, no registration required.

I'm using tags to do some Javascripting.

Is there any way that I can tell Craft to remove whitespace from {{ tag.name }} if the tag.name has spaces (for example 'apples and carrots'), and add dashes ('apples-and-carrots') ?

share|improve this question

1 Answer 1

up vote 8 down vote accepted

There are multiple ways to solve this:

Native:

Twigs url_encode filter:

{{ "apples and carrots"|url_encode }}
{# outputs "apples%20and%20carrots" #}

Twigs replace filter:

{{ "apples and carrots"|replace(' ', '-') }}
{# outputs "apples-and-carrots" #}

Plugins:

Twig PCRE Filters - Plugin:

{{ "apples and carrots"|preg_replace('/ /', '-') }}
{# outputs "apples-and-carrots" #}

Low Regex - Plugin:

{{ "apples and carrots"|regex('/ /', '-') }}
{# outputs "apples-and-carrots" #}

Slugify - Plugin:

{{ "apples and carrots"|slugify }}
{# outputs "apples-and-carrots" #}
share|improve this answer
2  
If you want to handle "apples & *!@#@! carrots" then you need the slugify plugin –  Marion Newlevant Jul 15 at 15:31
    
Great answer, Victor. –  Brad Bell Jul 15 at 19:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.