Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use custom django templatetag with django template if statement?

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.

like image 486
SnirD Avatar asked Dec 05 '25 17:12

SnirD


1 Answers

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 %}
like image 60
Yuji 'Tomita' Tomita Avatar answered Dec 08 '25 07:12

Yuji 'Tomita' Tomita



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!