1

I'm building a Craft website on Bootstrap 5. I want to split the output of a loop evenly across 2 seperate columns. There is an image column in the middle so the loop can't be continuos. The amount of items in the loop will vary so I need a flexible solution.

This is my current twig setup which outputs all entries in the table.

                {% for q in tableItem %}
                <div class="d-flex mb-5 table-item" data-aos="fade-up"> 
                    <div class="flex-shrink-0">
                    {% for asset in q.icon %}
                    <img src="{{ asset.url }}">
                    {% endfor %}
                    </div>
                <div class="flex-grow-1 ms-4">
                    <h5 class="mb-2">{{q.heading}} </h5>
                    <p>{{ q.description }}</p>
                </div>
                </div>
                {% endfor %}
            </div>

1 Answer 1

2

You can use the special loop variable to check if the current index is even or odd:

{% for q in tableItem %}
    {% if loop.index is even %}
        {# output even items #}
    {% endif %}
{% endfor %}

{% for q in tableItem %}
    {% if loop.index is odd %}
        {# output odd items #}
    {% endif %}
{% endfor %}

Though I would rethink this approach. You're tightly coupling your template logic to your styling, which usually results in HTML code that is semantically incorrect. Instead, I'd use a single loop to output the items in order and then user either either a grid to arrange items using grid-area or, if you're using the Bootstrap flexbox row, rearrange them with order-* classes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.