Django模板报错:无效endblock标签,期望empty或endfor
问题排查与修复
报错原因
你遇到的错误是因为外层的for循环未正确闭合:代码中{% for i in product|slice:"1:" %}这个循环开启后,没有对应的{% endfor %}标签来结束循环。模板解析器此时仍认为处于for循环的上下文里,遇到{% endblock %}时就会报错——它预期的是empty或endfor来结束当前循环,而非块结束标签。
另外你的代码里还存在HTML标签嵌套混乱的问题(比如多余的闭合</div>),但直接触发报错的是循环未闭合。
修复步骤
- 找到外层的
{% for i in product|slice:"1:" %},在内层循环的{% endfor %}之后、对应的</div>之前,补充{% endfor %}来闭合外层循环。 - 清理多余的HTML闭合标签,确保DOM结构嵌套正确。
修复后的关键循环部分代码示例:
{% for i in product|slice:"1:" %} <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 18rem;"> <img src='/media/{{i.image}}' class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> {% for i in product|slice:"1:" %} <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 18rem;"> <img src='{% static "shop/test.jpg" %}' class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> {% if forloop.counter|divisibleby:3 and forloop.counter > 0 and not forloop.last %} </div><div class="carousel-item"> {% endif%} {% endfor %} {% endfor %} <!-- 补充此行,闭合外层for循环 -->
额外提示
建议你编写模板时,对循环、块标签进行缩进对齐,这样能更直观地发现标签未闭合或嵌套错误的问题,避免类似报错重复出现。
内容的提问来源于stack exchange,提问作者Mahdin Ohi
相关产品推荐
相关产品推荐

