为什么我的 else 语句在 html 模板中不起作用。如果用户没有任何通知,它应该是显示文本“您没有任何通知”。我在我的 html 模板中使用 else 语句来显示文本,但为什么没有显示文本?这是我的代码:
{% 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 commnet
{%else%}
<h1>Don't have any notification</h1>
{% endif %}
{%endif%}
{%endfor%}
当用户没有任何通知时,我收到了空的 html 页面。如果用户有通知,那么它会显示,但我不明白为什么当用户没有任何通知时我的 else 语句不起作用。
您的 else 与 匹配{% if notification.notification_type == "Comment Approved" %}
,这意味着它将为博客作者是当前用户的每个通知呈现,并且通知类型为评论批准。
我会建议你在过滤视图(不是模板,Django模板应该不执行业务逻辑,只渲染逻辑)。这不仅更优雅,而且可能更高效,因为您可以在数据库端进行过滤并使用:
<!-- ↓ ↓ filter in the view -->
{% for notification in notifications %}
Your Blog Post {{notification.blog.title}} received new commnet
{% empty %}
<h1>Don't have any notification</h1>
{%endfor%}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句