access loop.index when within another loop in twig

前端 未结 2 1943
心在旅途
心在旅途 2020-12-30 18:34

How can i access the loop\'s index when i\'m in a second loop? like this:

      {% for i in range(0, 3) %}
          {% for j in range(0, 9) %}
           {{         


        
相关标签:
2条回答
  • 2020-12-30 19:14

    In fact there's no need to set an extra variable. For two nested loops twig provides the so called parent.loop context.

    To access the parents loop.index do this:

    {% for i in range(0, 3) %}
        {% for j in range(0, 9) %}
            {{ loop.parent.loop.index + loop.index }}
        {% endfor %}
    {% endfor %}
    

    Those two documentation entries should be helpful

    • the for loop variables
    • Accessing the parent Context in Nested Loops
    0 讨论(0)
  • 2020-12-30 19:17

    set a variable which hold the first loop.index

    {% for i in range(0, 3) %}
        {% set loop1 = loop.index %}
        {% for j in range(0, 9) %}
            {{ loop1 + loop.index }}
        {% endfor %}
    {% endfor %}
    
    0 讨论(0)
提交回复
热议问题