boyenec
boyenec

Reputation: 1617

Django else statement in html template not working

Why my else statement not working in html template. It should be display text "You don't have any notification" if user didn't have any notification. I am using else statement in my html template for showing the text but why text isn't showing? here is my code:

{% 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%}

when user don't have any notification I am getting empty html page. If user have notification then it's displaying but I am not understanding why my else statement not working when user don't have any notifications.

Upvotes: 1

Views: 245

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

Your else is matching with the {% if notification.notification_type == "Comment Approved" %}, this means that it will render for each notification that is for which the blog author is the current user, and the notification type is comment approved.

I would advise that you filter in the view (not the template, Django templates should not implement business logic, only rendering logic). This is not only more elegant, but likely more efficient, since you can do the filtering at the database side and work with:

<!--                   ↓           ↓ 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%}

Upvotes: 2

Related Questions