This may not be the most efficient approach for this specific case but I'm trying to learn how this might be done for other similar problems I might run across in the future so bear with me here.

I have a Global that creates links to social media sites on my profile page. My fields include icon (asset), name (text), url (text), and color (color). I have included the following at the top of my template:

{% set buttonCSS %}
    {% for block in contactLinks.contactLinks.type("contactLink") %}
    .{{ block.contactLinkName | lower }}:hover {
        background-color: {{ block.buttonColor }}
    {% endfor %}
{% endset %}

{% includeCss buttonCSS %}

This generates dynamic styles for each button at the top of my profile page so I can add links. My template then generates the links:

{% for block in contactLinks.contactLinks.type("contactLink") %}
<a href="{{ block.contactLinkUrl | entities }}" class="contact_link {{ block.contactLinkName | lower }}{% if loop.last %} last{% endif %}" target="_blank">
    <img src="{{ block.contactLinkIcon.first().url }}" class="contact_link_image" /><p class="contact_link_text">{{ block.contactLinkName }}</p>
{% endfor %}

Now, for the most part this works since social media sites tend to be one word but when I tried to use "Let's Talk" for my email link I run into problems with the CSS. What's the best way to strip the apostrophe and spaces from my class names?


You can chain filters to achieve what you want. The example for the twig replace filter in the Craft docs shows this in action.

So you could replace:

{{ block.contactLinkName | lower }}


{{ block.contactLinkName | lower | replace('/ /', '-') | replace("'","") }}
  • This worked for the most part. One of these days I'm going to learn RegEx but I was able to change the first replace to look for only spaces. As written this removes a lot more then just spaces. I'll look into a way to find punctuation and update this soon but for now this works. Sep 8 '14 at 16:39

I would use the slugify twig filter:

{{ block.contactLinkName | slugify }}

It will handle apostrophies, spaces, and anything else that might come along.


You could use the twig replace


{{ block.contactLinkName | replace({' ': -}) }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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