I created a paragraph named flight-search-info-block with two fields: field_svg_icon and field_teaser_text. Then I created a custom block, where that paragraph was added as an entity reference field. Now I want the structure as

<div class="item-wrap">
  <div class="item-img">...field_svg_img....</div>
  <div class="item-text">...field_teaser_text....</div>

I want to do this using hook_preprocess_paragraph. With this hook I was able to add the class to the paragraph wrapper div (yellow marked in the attached image). I also tried hook_preprocess_field, but again the class was added to the paragraph.

enter image description here enter image description here enter image description here

So how can I add the classes to the red marked elements?

1 Answer 1


Come from the other way. Come from the field. Check the parent entity (paragraph) type and then add the classes:

 * Implements hook_preprocess_HOOK().
function MYMODULE_preprocess_field__MYFIELD(&$variables) {
  /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
  $paragraph = $variables['element']['#object'];
  if ($paragraph->bundle() === 'foobar') {
    foreach ($variables['items'] as $delta => $item) {
      $variables['items'][$delta]['attributes']->addClass(['foo', 'bar', 'item-' . $delta]);

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.