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') ?
There are multiple ways to solve this:
Native:
{{ "apples and carrots"|url_encode }}
{# outputs "apples%20and%20carrots" #}
{{ "apples and carrots"|replace(' ', '-') }}
{# outputs "apples-and-carrots" #}
Plugins:
{{ "apples and carrots"|preg_replace('/ /', '-') }}
{# outputs "apples-and-carrots" #}
{{ "apples and carrots"|regex('/ /', '-') }}
{# outputs "apples-and-carrots" #}
{{ "apples and carrots"|slugify }}
{# outputs "apples-and-carrots" #}
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 }}
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.
Commented
Dec 3, 2015 at 6:08
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".
one more example with array parameter in replace method:
{{ "apples and carrots"|replace({" ":"-"}) }}
{# outputs "apples-and-carrots" #}