2

How would one construct this? I have built a little content builder and wish now to change the layout HTML on the fly when there are more than one matrix block.

In the example below, this is just one section of the builder and the one I would like to change.

Basically 'move' the block.text part above the image every 2nd time in the loop. I have looked at batch and loopindex but having trouble for the last few hours. Can someone please help with this?

Builder code:

{% case "splitImageAndText" %}
    <div class="grid-x align-center paddingBottom">
        {% set images = block.imagePart %}

        {% if images and images|length %}
            {% set image = block.imagePart.all() %}

            {# Loop through the images #}
            {% for image in images.all() %}
                <div class="cell medium-6 small-12">
                    <div class="bg-content" style="background-image:url('{{ image.getUrl() }}');"></div>
                </div>
            {% endfor %}
        {% endif %}

        <div class="cell medium-6 small-12 pull-left">
            {{ block.textPart }}
        </div>
    </div>
1

Building on Syversen's answer of how to achieve this, I'd make that text block a partial template so it's only written once and do the following:

{% case "splitImageAndText" %}
    <div class="grid-x align-center paddingBottom">
        {% set images = block.imagePart %}

        {% if loop.index is even %}
            {% include 'partials/text-block' %}
        {% endif %}

        {% if images and images|length %}
            {% set image = block.imagePart.all() %}

            {# Loop through the images #}
            {% for image in images.all() %}
                <div class="cell medium-6 small-12">
                    <div class="bg-content" style="background-image:url('{{ image.getUrl() }}');"></div>
                </div>
            {% endfor %}
        {% endif %}

        {% if loop.index is odd %}
            {% include 'partials/text-block' %}
        {% endif %}
    </div>

This way, if you ever need to alter the text block markup, it's only in one location instead of having any repeated markup. So in partials/text-block.twig, I'd have:

<div class="cell medium-6 small-12 pull-left">
    {{ block.textPart }}
</div>
  • 1
    And thank you Jay, that is very sensible, thank you too. – moondawg Aug 20 '18 at 17:34
1

I belive you can use {% if loop.index is even %} or {% if loop.index is odd %}

  • 1
    Ah yes, makes sense now, perfect, thank you. – moondawg Aug 20 '18 at 17:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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