How to use custom django templatetag with django's if statement template?

I created a django template tag that counts one of my custom lengths many-to-many by the user:

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 inside the template itself, I only want to show it to the user if it is greater than zero, so I tried:

{% ifnotequal unread_messages_count 0 %}
   some code...
{% endifnotequal %}

      

but obviously it didn't work. even with the '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 greater than 0 and only if there is one, present the user with some code (including the number in the variable itself). thank.

+3


source to share


2 answers


The easiest way is to use the destination 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 %}

      

+9


source


you can use django custom filter https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters

def unread_messages_count(user_id):
  # x = unread_count   ## you have the user_id
  return x

      



and in the template

{% if request.user.id|unread_messages_count > 0 %}
  some code...
{% endif %}

      

+2


source







All Articles