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

时光怂恿深爱的人放手 提交于 2019-12-10 10:15:40

问题


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.


回答1:


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



回答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 %}


来源:https://stackoverflow.com/questions/14767516/how-to-use-custom-django-templatetag-with-django-template-if-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!