I've made a django template tag that counts one of my custom user many-to-many field length:
from django import template
register = template.Library()
@register.simple_tag(takes_context=True)
def unread_messages_count(context):
user = context['request'].user
return len(user.messages_unread.all())
and within the template itself, I want to show it to user only if it's larger than zero, so I tried:
{% ifnotequal unread_messages_count 0 %}
some code...
{% endifnotequal %}
but obviously it didn't work. not even with a 'with' statement:
{% with unread_messages_count as unread_count %}
{% ifnotequal unread_count 0 %}
some code...
{% endifnotequal %}
{% endwith %}
How can I check that the variable is larger than 0 and only if it is, present some code to the user (including the number in the variable itself). thanks.
The easiest way would be to use an assignment tag..
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#assignment-tags
@register.assignment_tag(takes_context=True)
def unread_messages_count(context):
user = context['request'].user
return len(user.messages_unread.all())
{% unread_messages_count as cnt %}
{% if cnt %}
foo
{% endif %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With