Score:1

Adding a class to an image using preprocess function

ck flag

I am having trouble adding a class to an image using a preprocessor function in Drupal 9. Specifically, I only want certain images to have that class added. The image is being added using paragraphs.

I've tried a few variations of the following and cannot seem to get class added. I've also tried using ['#item'] but it causes an error.

function confluence_preprocess_field__paragraph__field_card_image(&$variables) {    
    foreach($variables['items'] as $key => $item){
        $variables['items'][ $key ]['content']['item']['class'] = 'card-img-top';
    }
}
Score:0
cn flag

You can add it via the content's #item_attributes array like so:

foreach($variables['items'] as $key => $item){
  $variables['items'][$key]['content']['#item_attributes']['class'][] = 'card-img-top';
}
Vince Saseniuk avatar
ck flag
Fantastic, it works. Thank you so much.
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.