Search code examples
htmlnested-loops

Is there a way to get the values of outer loops when using nested loops in html?


Currently the id of the popup is used repeatedly and the Edit button only works inside the first "project" . I would like to use the values of the outer loops as well to create a unique id for the popup. Are there better ways to do this?

The current layout lists all projects inside each project all the orders and inside each order the line items.

Example:

PROJECT NAME
   --> ORDER NUMBER
      --> LINE ITEM
      --> LINE ITEM
   --> ORDER NUMBER
      --> LINE ITEM
      --> LINE ITEM

Here is my code:

{% for project in projects %}
  ...

  {% for order in project.orders %}
    ...
    
    {% for lineItem in order.line_items %}
    <td>
      <button onclick="editRow(this, '{{ loop.index }}'), openPopup('{{ loop.index }}')" class="remove-button" style="background: #00e50b">Edit</button>
      <div class="popup" id="popup{{ loop.index }}">
        <div class="popup-content">
          <h2 style='color: #000000'>Edit New ETA / Comments</h2>
          <form action="/manage_stock" method="POST" style="display: none;">
            ...
          </form>
        </div>
      </div>
    </td>
    {% endfor %}

    ...
  {% endfor %}

  ...
{% endfor %}

Solution

  • You can use loop.parent.loop.index and/or loop.parent.loop.parent.loop.index to access to outer loop indexes for Twig

    EDIT

    So, if you are using Jinja and it doesn't support parent loop index, you can try to save it in a variable:

    {% for project in projects %}
    
       {% set project_index = loop.index %}
    
       {% for order in project.orders %}
    
          {% set order_index = loop.index %}
        
          {% for lineItem in order.line_items %}
    
          Composite index: {{ project_index }}-{{ order_index }}-{{ loop.index }} 
    
          {% endfor %}
    
       {% endfor %}
    
    {% endfor %}