[英]how to use custom django templatetag with django template if statement?
我制作了一個django模板標簽,用於計算我的一個自定義用戶的多對多字段長度:
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())
並且在模板本身內,我想只有當它大於零時才顯示給用戶,所以我試過:
{% ifnotequal unread_messages_count 0 %}
some code...
{% endifnotequal %}
但顯然它沒有用。 甚至沒有'with'聲明:
{% with unread_messages_count as unread_count %}
{% ifnotequal unread_count 0 %}
some code...
{% endifnotequal %}
{% endwith %}
如何檢查變量是否大於0,並且只有當變量大於0時,才向用戶顯示一些代碼(包括變量本身中的數字)。 謝謝。
最簡單的方法是使用賦值標記..
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 %}
你可以使用django自定義過濾器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
並在模板中
{% if request.user.id|unread_messages_count > 0 %}
some code...
{% endif %}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.