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.

有帮助吗?

解决方案 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.

其他提示

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 %}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top