You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 16:27:01