Ad

How To Display Bootstrap Carousel With 3 Items Per Slide Using Liquid Shopify

I am trying to create a bootstrap carousel that displays 3 items per slide using Liquid. This is my sample code

  <div class="item active">
    {% for course in courses %}
      {% if forloop.index >= 1 and forloop.index <= 3 %}
        <div class="col-md-4">
          {% include "courses/box", course: course %}
        </div>
      {% endif %}
    {% endfor %}
  </div>

  <div class="item">
    {% for course in courses %}
      {% if forloop.index >= 4 and forloop.index <= 6 %}
        <div class="col-md-4">
          {% include "courses/box", course: course %}
        </div>
      {% endif %}
    {% endfor %}
  </div>

At the moment, this code works but it is not dynamic. I would have to repeat the code for each loop and this becomes difficult when there are lot of courses/items that needs to be displayed.

I am wondering how I can somehow increment the forloop so it only displays 3 items/courses per slide. Kindly let me know if you need more information or code samples.

Ad

Answer

There might be a better options but this is what I figured.

<div class="item active">
{% for course in courses %}
  {%- assign module = forloop.index | modulo: 3 -%}

  {%- if module == 1 -%}
    {%- unless forloop.first -%}
    <div class="item">
    {% endunless %}
  {%- endif -%}

    <div class="col-md-4">
      {% include "courses/box", course: course %}
    </div>

  {%- if module == 0 -%}
    {%- unless forloop.last -%}
      </div>
    {%- endunless -%}
  {%- endif -%}

{% endfor %}
</div>

To break it down.

  1. I wrap the whole logic in the <div class="item active"> and close it at the bottom.

  2. I loop all of the courses

  3. I assign a module variable which returns the module of 3 from the current forloop.index. So if you are on 3,6,9 etc.. index it will return 0.

  4. I check if the module is 1 and if it's not the first loop ( this is because we already create the <div class="item active"> and we don't need another one and the if will be true when you are on the 4th loop, 7th loop and so on, a.k.a the place we need to put a new <div class="item"> )

  5. I add the <div class="col-md-4">{% include "courses/box", course: course %}</div>

  6. Finally I check if the module is equal to 0 or if this is the last loop ( because if it's the last loop we will have two </div> at the end ) and add the closing <div>.

Ad
source: stackoverflow.com
Ad