3

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.

2 Answers 2

9

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 %}
Sign up to request clarification or add additional context in comments.

1 Comment

Deprecated since version 1.9: "simple_tag can now store results in a template variable and should be used instead."
2

you can use a 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 %}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.