Using Class Values from Entities as CSS Class Names with Twig
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 |render
twig 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.