Django报错:TemplateSyntaxError at / Invalid block tag: 'else', expected 'empty' or 'endfor'

这是一个很小、很容易忽略但却不易查找的错误,困扰了我好几个小时,原代码如下:

Django项目中templates下的html模板index.html

 
  1. <!DOCTYPE html>

  2. <html lang="en">

  3. <head>

  4. <meta charset="UTF-8">

  5. <title>Title</title>

  6. </head>

  7. <body>

  8. <a href="{% url 'booktest:show' '456' '789'%}">展示</a>

  9. <hr>

  10. {{hero.showname}}

  11. <hr>

  12. 奇数行显示为蓝色,偶数行显示为红色

  13. <hr>

  14. <ul>

  15. {% for hero in list %}

  16. {% if forloop.counter|divisibleby:"2" % }

  17. <li style="color:red">{{ forloop.counter }}: {{ hero.showname }}</li>

  18. {% else %}

  19. <li style="color:blue">{{ forloop.counter }}: {{ hero.showname }}</li>

  20. {% endif %}

  21.  
  22. {% empty %}

  23. <li>啥也没找到</li>

  24. {% endfor %}

  25. </ul>

  26. </body>

  27. </html>

运行一直报如下错误:

Django报错:TemplateSyntaxError at / Invalid block tag: 'else', expected 'empty' or 'endfor'

Django报错:TemplateSyntaxError at / Invalid block tag: 'else', expected 'empty' or 'endfor'

图二中18行变红,但是看了几遍逻辑关系都没有问题,后来受一篇相似错误文章的启发,检查到第16行,原来错误在于此处:

Django报错:TemplateSyntaxError at / Invalid block tag: 'else', expected 'empty' or 'endfor'

对,就是第二个百分号和右花括号中间多了一个空格,去掉空格后,问题顺利解决,不再报错!

Django报错:TemplateSyntaxError at / Invalid block tag: 'else', expected 'empty' or 'endfor'

好吧,以后敲代码一定要仔细。

参考文章:https://*.com/questions/27215623/templatesyntaxerror-invalid-block-tag-else-expected-endif