1

I'm getting incorrect loop.index results with the following code. It returns "1" for each entry returned. Is there a different way this needs to be written?

{% for order in orders %}
    {% for refund in order.transactions if refund.type == "refund" %}
        {{ loop.index  }}
    {% endfor %}
{% endfor %}
  • You want the loop index of the inner for loop or do you want the loop index of the outer? If each order only has 1 transaction, I'd expect your code to output 1, orders number of times. – Brad Bell Nov 14 '17 at 21:45
3

I'm guessing you want to display the loop index of the outer for loop.

To do that, Twig provides a loop.parent context.

{% for order in orders %}
    {% for refund in order.transactions if refund.type == "refund" %}
        {{ loop.parent.loop.index  }}
    {% endfor %}
{% endfor %}

If you're looking to get the total number of times the inner loop gets hit, then something like this should work:

{% set loopCount = 0 %}

{% for order in orders %}
    {% for refund in order.transactions if refund.type == "refund" %}
        {% set loopCount = loopCount + 1 %}
        {{ loopCount  }}
    {% endfor %}
{% endfor %}
  • I was looking for the inner loop count. I see your comment above and I think I understand what's happening now... What I'm looking to do is number a table column from 1...XXX. Let me try {{ loop.parent.loop.index }} – Anna_MediaGirl Nov 15 '17 at 1:18
  • Negative... Using {{ loop.parent.loop.index }} didn't get me the count numbers either... I'll see if I can return a row number another way. – Anna_MediaGirl Nov 15 '17 at 1:49
  • Hrm... check my edit and see if that's what you're looking for. – Brad Bell Nov 15 '17 at 20:34
  • That did the trick! – Anna_MediaGirl Nov 16 '17 at 1:45

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.