Cape Cod, Massachusetts 41°39'20.7"N 70°09'53.0"W
Back to blog Drupal Development

One or Multiple: a Bootstrap Carousel from a multiple-value Drupal field

One or Multiple: a Bootstrap Carousel from a multiple-value Drupal field

Building on last week’s Paragraphs carousel, here’s how to drive a Bootstrap Carousel from a multiple-value Drupal field — a useful pattern when a single field (like a Featured Image field) needs to do double duty as the page hero and an Open Graph image.

The problem

You have a field that allows multiple values. Sometimes there’s one value, sometimes there are several. When there’s one, you want a static image. When there are several, you want a carousel. The challenge: a single Twig template to handle both cases.

The Twig approach

The key is checking the item count in the field array before deciding which markup to output:

{% set items = field_images %}
{% if items|length > 1 %}
  {# Carousel markup #}
  <div id="carousel-{{ entity.id }}" class="carousel slide" data-ride="carousel">
    <ol class="carousel-indicators">
      {% for key, item in items %}
        <li data-target="#carousel-{{ entity.id }}" data-slide-to="{{ key }}"
            class="{{ key == 0 ? 'active' : '' }}"></li>
      {% endfor %}
    </ol>
    <div class="carousel-inner">
      {% for key, item in items %}
        <div class="item {{ key == 0 ? 'active' : '' }}">
          {{ item }}
        </div>
      {% endfor %}
    </div>
  </div>
{% else %}
  {# Single image #}
  {{ items[0] }}
{% endif %}

Why this matters for Open Graph

If your Featured Image field is also the OG image source, you only want the first image to be the OG tag — regardless of how many are in the field. Handle this in your html.html.twig by grabbing field_images[0] directly, bypassing the carousel template entirely.

This keeps your structured metadata clean while still giving editors a flexible carousel on the page.