Customize Carousel Paragraph Type

In this video, you’ll learn how to create an actual carousel.

Code

paras_bootstrap.theme

/**
 * Implements hook_preprocess_paragraph__carousel().
 */
function paras_bootstrap_preprocess_paragraph__carousel(&$variables) {
  $slides = [];
  $paragraph = $variables['paragraph'];
  if (!$paragraph->field_paragraphs->isEmpty()) {
    $paragraphs = $paragraph->field_paragraphs->referencedEntities();
    foreach ($paragraphs as $slide_paragraph) {
      $item = [];
      if (!$slide_paragraph->field_title->isEmpty()) {
        $item['title'] = $slide_paragraph->field_title->value;
      }
      if (!$slide_paragraph->field_body->isEmpty()) {
        $item['description'] = [
          '#type' => 'processed_text',
          '#text' => $slide_paragraph->field_body->value,
          '#format' => $slide_paragraph->field_body->format,
        ];
      }
      if (!$slide_paragraph->field_image->isEmpty()) {
        // Get image field.
        $image_field = $slide_paragraph->field_image;
        $image_style = 'banner';
        // Generate image URL.
        $item['image'] = [
          '#theme' => 'image_style',
          '#style_name' => $image_style,
        ];
        // Do not output an empty 'title' attribute.
        if (\Drupal\Component\Utility\Unicode::strlen($image_field->title) != 0) {
          $item['image']['#title'] = $image_field->title;
        }
        if (($entity = $image_field->entity) && empty($image_field->uri)) {
          $item['image']['#uri'] = $entity->getFileUri();
        }
        else {
          $item['image']['#uri'] = $image_field->uri;
        }
        foreach (array('width', 'height', 'alt') as $key) {
          $item['image']["#$key"] = $image_field->$key;
        }
      }
      if (!empty($item)) {
        $slides[] = $item;
      }
    }
  }
  if(!empty($slides)) {
    $variables['content']['bootstrap_carousel'] = [
      '#theme' => 'bootstrap_carousel',
      '#slides' => $slides,
    ];
    hide($variables['content']['field_paragraphs']);
  }
}

style.css

.paragraph--type--carousel .carousel-inner img {
  width: 100%;
}

Commands

drupal cache:rebuild all