Customize Banner Paragraph Type

In this video, we’ll customize how the banner paragraph is rendered using its preprocess function.

Code

paras_bootstrap.theme

/**
 * Implements hook_preprocess_paragraph__banner().
 */
function paras_bootstrap_preprocess_paragraph__banner(&$variables) {
  $paragraph = $variables['paragraph'];
  // If banner image and nested paragraphs are present.
  if (!$paragraph->field_image->isEmpty() && !$paragraph->field_paragraphs->isEmpty()) {
    $image_style = 'banner';
    // Generate image URL.
    if (!empty($image_style)) {
      $banner_image_uri = $paragraph->field_image->entity->getFileUri();
      $banner_image = DrupalimageEntityImageStyle::load($image_style)->buildUrl($banner_image_uri);
    }
    else {
      $banner_image = $paragraph->field_image->entity->url();
    }
    // Add image as background.
    $variables['attributes']['style'][] = 'background-image: url("' . $banner_image . '");';
    $variables['attributes']['style'][] = 'background-size: cover;background-position: center center;';
    // Hide the normal <img> tag.
    hide($variables['content']['field_image']);
  }
  // Check if banner color is empty.
  if (!$paragraph->field_banner_color->isEmpty()) {
    $banner_color = $paragraph->field_banner_color->getValue();
    $banner_color = reset($banner_color);
    $variables['attributes']['style'][] = 'background: ' . $banner_color['color'] . ';';
  }
  // Check if text color is empty.
  if (!$paragraph->field_text_color->isEmpty()) {
    $text_color = $paragraph->field_text_color->getValue();
    $text_color = reset($text_color);
    $variables['attributes']['style'][] = 'color: ' . $text_color['color'] . ';';
  }
}

style.css

.paragraph--type--banner .field--name-field-image img {
  width: 100%;
}
Scroll to Top