Django HTML模板else语句不生效,无通知时不显示提示如何解决?
问题根因
- 语句配对逻辑错误:你写的
else是和判断通知类型的{% if notification.notification_type == "Comment Approved" %}绑定的,只会在「存在当前通知、且通知类型不是Comment Approved」时触发,和「用户无通知」的场景没有任何关联 - 空集合不会执行循环内容:当用户没有任何通知时,
notifications为空,整个for循环内部的代码完全不会运行,自然不会输出任何内容
修复代码
模板引擎的for循环支持空集合分支,专门用于处理循环对象为空的场景,调整后的代码如下:
{% for notification in notifications %} {% if user.id == notification.blog.author.id %} {% if notification.notification_type == "Comment Approved" %} Your Blog Post {{notification.blog.title}} received new comment {% endif %} {% endif %} {% empty %} <strong>你没有任何通知</strong> {% endfor %}
内容的提问来源于stack exchange,提问作者boyenec
相关产品推荐
相关产品推荐

