0

I have a typical content type, with a field, let's say field_name.

I can output each field using the field.html.twig file. In the file, to output each item, there is a line

<div{{ item.attributes }}>{{ item.content }}</div>

So how can I set item.attributes, to output, say, the machine name of the field, so that my output is:

<div class="field_name">My Name</div>

I suspect it has to do with using the:

function theme_preprocess_field(&$variables) {

$item['content']['#item_attributes']['class'][] = $variables['field_name'];

Is this correct? Where do I go from here? How can I make this work?

Thanks!!

1 Answer 1

1

How can I add classes to an item in field.html.twig?

Use attributes.addClass():

<div{{ item.attributes.addClass(field_name|clean_class) }}>{{ item.content }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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