Nesting level too deep when looping through matrix blocks I'm running into a nesting level error when looping through matrix blocks, and I can't quite figure out what the problem is.

The problem arises when I use a variable to track the type of the previous element in the matrix. I want to be able to know within the sub-template that an element is the nth of the same type (for adding a container around some matrix block types to group them).

If I replace line 7 below with, eg. {% set n = (element.type == 'product') ? n + 1 : 0 %} (ie. a named element type rather than a variable) it works as expected, but as soon as I compare element.type to prevElementType I get a Fatal error: Nesting level too deep - recursive dependency? error. Some of the partial templates that may be included in the loop check prevElementType, but none of them modify it, so I can't see what's causing the recursion. I'd be grateful for any help with this.

{% if entry.contentBlocks is not empty %}
  {% set prevElementType = false %}

  {% for element in entry.contentBlocks %}

  {# Let's use a counter for multiple blocks of the same type: #}
  {% set n = (element.type == prevElementType) ? n + 1 : 1 %}

  {# Include the partial for this block: #}
  {% include "_pageelements/" ~ element.type|lower %}

  {# Track this element's type for the next iteration: #}
  {% set prevElementType = element.type %}

  {% endfor %}
{% endif %}
element.type is not a simple string (add {{dump(element.type)}} to your loop to see this). What you should use is element.type.handle. So the assignment is:

{% set prevElementType = element.type.handle %}


And the comparison (now of two strings, so no recursion) is:

element.type.handle == prevElementType