Using field values as CSS class names in Drupal 8 with Twig

Sarah Carney
2 min readFeb 25, 2019

I have a Custom Block Type and I made some fields to control the style of the card by using the field values as CSS classes in the block’s template.

Or, how to use a field value as a class name in Drupal 8.

EDIT: 3 Feb 2020 — Kaleem Clarkson has good feedback in the responses on a cleaner way to do this which uses the clean_classtwig filter: https://medium.com/@kaleemclarkson/using-class-values-from-entities-as-css-class-names-with-twig-277a18a5fe6f

Thank you, Kaleem!

Leaving the rest of this article for context.

So I have:

  • Custom Block Type for a card
  • A List field where the keys are my CSS class names which I will use to change the card’s visual design. Like, card_red
  • A custom theme template for the block.

I like to apply my CSS classes with an array where card_classes is the variable name I chose.

{% set card_classes = [
'my_class',
'other-class',
'classsssss'
]
%}
<div{{ attributes.addClass(card_classes) }}>
...

But if you do this, Drupal shouts at you so much.

{% set card_classes = [
'my_class',
{{ content.field_my_list_field_name }}
]
%}

Here is an answer

{% set card_classes = [
'my_class',
(render_var(content.field_my_list_field_name.0))
]
%}
  • render_var is one of Drupal 8’s TwigExtention functions. I think it ‘renders’ the ‘variable’.
  • content.field_my_list_field_name.0 is how to get the first value of a List field.

This will produce:

<div class="my_class list-field-class">

Read more about how to pull field values in Twig:

How to create your own Drupal 8 Custom Block Type templates:

I don’t know exactly why it works but if you are trying to use a field variable as a class name, here we go.

--

--