One or Multiple. Make a Bootstrap Carousel from a Multiple Value Drupal Field

Earlier this week I wrote how to create a Bootstrap Carousel using the Drupal Paragraphs module.  We can modify this approach to add a Bootstrap Carousel on a field.  I use this most on nodes that have a Featured Image field, one where we can use as a hero image, and one where we can set the Open Graph Meta image on a per node basis.

Thanks to social media outlets like Facebook, LinkedIn, and Twitter, every piece of content published to the web should have an image attached to it, define by the og:image meta tag.  But what happens when the content has or deserves more than one image?  If the field allows multiple, we can display them as a carousel/slideshow.

While I am discussing images in this blog post, this technique could be used for any type of field.  And even though I develop using the Bootstrap front end framework, the same theory could be applied to other frameworks and javascripts like the Slick carousel.  You would just need to change the markup to fit your specific framework.

So, all we need is a multiple value field.  Once we have defined which field that is, take a look at this markup and replace your template's markup with it.  The file name would be field--FIELD-NAME.html.twig

The first IF statement simply says if there is more then one, print this Bootstrap markup. If there aren't, just print the output with no markup.

We then use Twig Set to set a variable to a random number using the Twig Random function.  We do this to ensure each carousel is unique in case other fields on the page are also carousels.

We then loop through the Slides for the carousel indicators and repeat the loop for the carousel items, adding a unique class using the key making them unique also.  This allows the indicators and Next/Previous links to step through, and gives additional slide classes to style if needed.

While the above uses Drupal 8 and Twig, here is a template that can be used in Drupal 7 which uses PHP and JavaScript to achieve a similar outcome.  Inline comments define what each line does.