14

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') ?

4 Answers 4

25

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" #}
1
  • 2
    If you want to handle "apples & *!@#@! carrots" then you need the slugify plugin Commented Jul 15, 2014 at 15:31
15

Craft has a filter for "Kebab Case", which I think is what you need. It strips out punctuation and replaces spaces with dashes. Useful if you need to format a field as a HTML attribute.

{{ tag.name|kebab }}
1
  • 1
    Perfect answer. Worth noting that kebab didn't exist at the time this question was originally asked. It was added on Jun 2, 2015, when Craft 2.4.2664 was released.
    – Lindsey D
    Commented Dec 3, 2015 at 6:08
9

I'm not sure if this feature is newer than this question but you can also say {{ tag.slug }} to get apples-and-carrots. All letters become lowercase as well so the result is more "scripting-friendly".

1
  • 1
    This should be the accepted answer.
    – carlcs
    Commented Dec 3, 2015 at 7:41
1

one more example with array parameter in replace method:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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