【问题标题】:Trouble with nested for-loops in djangodjango中嵌套for循环的问题
【发布时间】:2016-05-20 08:49:49
【问题描述】:

我在尝试找出 django 中的嵌套 for 循环时遇到了麻烦。

它在第三个 endfor 块上不断向我抛出一个错误,告诉我“第 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>

【问题讨论】:

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


    【解决方案1】:

    在您的内部循环中,您将覆盖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 %}
    

    应该可以解决的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-02
      相关资源
      最近更新 更多