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.

Tom De Smet
  • 1,456
  • 8
  • 28
Jeffrey Q
  • 11
  • 2
  • This question has some tips on how to dynamically wrap block types that are of the same type if they’re next to each other. https://craftcms.stackexchange.com/q/1745/50 – Simon Kuran Oct 28 '18 at 08:20

1 Answers1

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 %}
Tom De Smet
  • 1,456
  • 8
  • 28