Skip to content

Instantly share code, notes, and snippets.

@setiawanjemy88
Forked from danieltott/matrix-collection.twig
Created August 11, 2021 01:03
Show Gist options
  • Save setiawanjemy88/7767fe152688e4a2a8e9f49e07e5cd22 to your computer and use it in GitHub Desktop.
Save setiawanjemy88/7767fe152688e4a2a8e9f49e07e5cd22 to your computer and use it in GitHub Desktop.
Matrix in Matrix Workaround
{% macro outputTiles(tileList) %}
{# use macro to keep it DRY #}
<div class="tiles">
{% for tile in tileList %}
<div class="tile">{{ tile.tileTitle }}</div>
{% endfor %}
</div>
{% endmacro %}
{% if entry.testMatrix is defined %}
{# start with empty array #}
{% set tileList = [] %}
{# loop through matrix blocks like normal #}
{% for block in entry.testMatrix %}
{% if block.type != "tile" and tileList|length %}
{# here's where we actually output the tile group #}
{{ _self.outputTiles(tileList) }}
{# once we've outputted the tiles, empty the list #}
{% set tileList = [] %}
{% endif %}
{# normal switch on block.type #}
{% switch block.type %}
{% case "textBlock" %}
<div class="textBlock">Text Block</div>
{% case "imageBlock" %}
<div class="imageBlock">Image Block</div>
{% case "callToAction" %}
<div class="callToAction">Call to Action</div>
{% case "tile" %}
{# instead of outputting anything, we save this tile to our list for later outputting #}
{% set tileList = tileList|merge([block]) %}
{% endswitch %}
{% endfor %}
{# once we've finished the loop, we output any tiles that were at the end of the loop #}
{% if tileList|length %}
{{ _self.outputTiles(tileList) }}
{% set tileList = [] %}
{% endif %}
{% endif %}
{# that's it! #}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment