1

I made a template including a matrix field. I want to wrap all occurrences of a certain block type into a <ul> element. How can I do this?

My current code:

 {% for block in entry.matrixField.all() %}
        {% switch block.type %}
            {% case 'blockType1' %}
            <div>
                {{ block.field }}
            </div>
            {% case 'blockType2' %}
            <div>
                {{ block.field }}
            </div>
            {% case 'blockType3' %}
            <ul>
                <li>
                    {{ block.field }}
                </li>
            </ul>
        {% endswitch %}
    {% endfor %}

Current output:

<ul>
    <li>blockfield</li>
</ul>
<ul>
    <li>blockfield</li>
</ul>
<ul>
    <li>blockfield</li>
</ul>

But I want my output like this:

<ul>
    <li>blockfield</li>
    <li>blockfield</li>
    <li>blockfield</li>
</ul>

That is, I want the ul tag to follow the loop of blockType3.

1

1 Answer 1

2

A possible solution could be this: Instead of outputting your blockType3 immediately, save all blockType3 ID's in an array. When your loop has finished (check for loop.last) output all the blocktypes from the array at once.

This code is just as an example (untested):

{% set arrBlockType3 = [] %}
{% for block in entry.matrixField.all() %}
    {% switch block.type %}
        {% case 'blockType1' %}
            <div>
                {{ block.field }}
            </div>
            {% case 'blockType2' %}
            <div>
                {{ block.field }}
            </div>
            {% case 'blockType3' %}
                {% set arrBlockType3 = arrBlockType3 | merge([block.id]) %}
    {% endswitch %}
    {% if loop.last %}
        <ul>
        {% for id in arrBlockType3 %}
            {% set block = entry.matrixField.id(id).first() %}
            <li>{{ block.field }}</li>
        {% endfor %}
        </ul>
    {% endif %}
{% endfor %}

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.