Using Class Values from Entities as CSS Class Names with Twig

Kaleem Clarkson
1 min readSep 5, 2019

Sarah Carney, please keep these posts coming they save me every day :)

I needed to add a class from a custom entity that provided printed the name of the field. Using the trusty solution Sarah Carney provided on her post was once again a savior. The one thing that I needed then was to figure out how to add a hyphen when there are two names. Well, wouldn’t you know that there is a twig filter that does this for you? Its called |clean_class .

After going through a code review with a colleages at work they suggested changing the syntax to be more in line with the Drupal twig way by using the |rendertwig filter.

{% set iclass = [content.custom_entity.0|render|clean_class,
'another-class',
]%}<div{{ attributes.addClass(iclass) }}>{{ content.message }}</div>
/// HTML RESULTS //
<div class="my-four-word-class another-class"><p>A new message that says Drupal is awesome</p></div>

As you can see from the example above, the render filter and the clean class filter provide the desired requirements. The great thing about Drupal is that there are so many ways to achieve the desired result.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Kaleem Clarkson
Kaleem Clarkson

Written by Kaleem Clarkson

Co-Founder & COO of @BlendMeInc, Advocate for Location Independent Workplaces, Drupal Front-End Developer, Community Builder. http://blendmeinc.com

Responses (2)

Write a response