-1

I'm having trouble trying to figure out nested for-loops in django.

It keeps throwing me an error on the third endfor-block, telling me "Invalid block tag on line 23: 'endfor', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag?", but that makes no sense to me.

The code pretty much looks like this:

<body>
    <h1>Table</h1>
    {% if items1 %}
        {% if items2 and items3 and items4 %}
          <table style="width:90%">
            <tr>
              {% for item4 in items4 %}
                <th>{{ item4 }}</th>
              {% endfor %}
            </tr>
              {% for item2 in items2 %}
                <tr>
                {for item4 in items4}
                  <td>{{ item2 }}</td>
                {% endfor %}
                </tr>
              {% endfor %}
          </ul>
        {% else %}
            Error 1.
        {% endif %}
      {% else %}
          Error 2.
      {% endif %}
</body>
GZ_0
  • 27
  • 5

1 Answers1

0

In your inner loop, you are overwriting item4.

        <tr>
          {% for item4 in items4 %}
            <th>{{ item4 }}</th>
          {% endfor %}
        </tr>
          {% for item2 in items2 %}
            <tr>
            {for item4 in items4}
              <td>{{ item2 }}</td>
            {% endfor %}
            </tr>
          {% endfor %}
      </ul>

Also, this line

{for item4 in items4}

dosn't have valid block tags, but there is a closing {% endfor %} blocktag. So Django finds one too many {% endfor %} tags.

Change this part

{for item4 in items4}
    <td>{{ item2 }}</td>
{% endfor %}

into

{% for item4_2 in items4% }
    <td>{{ item2 }}</td>
{% endfor %}

That should solve it.

C14L
  • 12,153
  • 4
  • 39
  • 52