문제

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