Score:0

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

in flag

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!!

Score:1
cn flag

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 }}
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.