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 %}
  • (Incidentally, I can get around the problem by explicitly listing the element types that might need a container - eg. if (element.type == 'product' or element.type == ' ... '), but ideally I'd still like to be able to track "nth of type" generically, so I'd like to get to the bottom of this) – Nick F Jun 23 '15 at 10:44
  • 1
    What does {{dump(element.type)}} show you? If it's not a simple string, you may want to use element.type.handle – Marion Newlevant Jun 23 '15 at 16:39
  • Oh gosh, you're absolutely right. Because the comparison of element.type to a string worked, I assumed element.type was itself a simple string. If you put the above comment as an answer, I'll mark it accepted. Thanks! – Nick F Jun 23 '15 at 17:13
  • Twig has an === operator for when you want to avoid those type coercions: twig.sensiolabs.org/doc/tests/sameas.html – Marion Newlevant Jun 23 '15 at 17:21
  • Ah, thanks - that's also good to know. I always use === when writing code, but hadn't realised that option was available in Twig. – Nick F Jun 23 '15 at 17:54

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
| improve this answer | |

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.