在django中嵌套for循环的麻烦

时间:2016-05-20 08:49:50

标签: django python-3.x django-1.9

我无法在django中找出嵌套的for循环。

它一直在第三个endfor-block上抛出一个错误,告诉我“第23行的无效块标记:'endfor',预期'elif','else'或'endif'。你忘了注册或加载这个标签?“,但这对我没有意义。

代码看起来很像:

<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>

1 个答案:

答案 0 :(得分:0)

在你的内循环中,你覆盖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>

此外,这一行

{for item4 in items4}

没有有效的块标签,但是有一个关闭{%endfor%}的阻止标签。所以Django找到了太多{%endfor%}标签。

更改此部分

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

进入

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

那应该解决它。