data/admin/2020/10/bootstrap-carousel-two-items-slide.jpg

Implementing two items per slide inside a bootstrap carousel, dynamically loaded from the controller method. This solution uses .NET C# for it's backend and server-based code, however, this solution should be easily transferable across stacks. (It's the logic that counts :) )

The Code

*Note, view the fiddle on full screen to see the items side by side (currently responding to a reduced screensize)

Solution Explained

The key to this solution leans on the the .Skip() and .Take() LINQ methods.

We iterate through a list of items loaded from the controller 2 at a time and take 2 items loading them into a variable, items.

for (int i = 0; i < Model.CarouselItemList.Count; i += 2)
{
 var items = Model.CarouselItemList.Skip(i).Take(2).ToList();  
 
 //.. decorate the slide 

}
 

For each iteration, we skip the number of items iterated so far using the for loop's index variable. That's the genius of this solution.

We then split the carousel item evenly into two using bootstrap's grid system. And retrieve the relevant slide item using items[0] and items[1].

I've also put in a bit of custom css .carousel-item-inner to add some padding.

div class="carousel-item @(items[0] == Model.CarouselItemList[0] ? "active" : "")"> applies the .active class to the first items in the list, .active represents the first item in the Carousel and must be added to at least one of the slides, otherwise the carousel will not be visible.