Question

I would like to do this inside a for loop

{% if count % 2 == 0 %}
    <div class="col-md-6"><!--start block-->
        <div class="item-small gutter-bottom">
            <img src="{{ item.image_url }}"/>
            <div class="item-title">{{ item.name }}</div>
        </div>
{% else %}
        <div class="item-small gutter-bottom">
            <img src="{{ item.image_url }}"/>
            <div class="course-title">{{ item.name }}</div>
        </div>
    </div><!--end block-->
{% endif %}

where I put an additional div wrapping every two items. However, when rendered in HTML, the closing tags went all wrong and the output is not pleasant.

Was it helpful?

Solution 2

I'd do this in this way (I put an own example for the loop):

{% for i in 0..9 %}
    {% if loop.index0 % 2 == 0 %}
    <div class="col-md-6"><!--start block-->
        <div class="item-small gutter-bottom">
            <img src="{{ item.image_url }}"/>
            <div class="item-title">{{ item.name }}</div>
        </div>
    {% else %}
        <div class="item-small gutter-bottom">
            <img src="{{ item.image_url }}"/>
            <div class="course-title">{{ item.name }}</div>
        </div>
    </div><!--end block-->
    {% endif %}
{% endfor %}

You need to take care about the indexes of the loop, because if the 'if' code is not rendered first, your rendered html wouldn't be good, and the same occurs if in the last iteration the 'else' code is not rendered.

OTHER TIPS

You should use twig's batch method instead.

{% for row in items|batch(2) %}

    <div class="col-md-6"><!--start block-->

        {% for item in row %}

            <div class="item-small gutter-bottom">
                <img src="{{ item.image_url }}"/>
                <div class="item-title">{{ item.name }}</div>
            </div>

        {% endfor %}

    </div><!--end block-->

{% endfor %}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top