我制作了一个 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 %}
关于python - 如何在 django 模板 if 语句中使用自定义 django templatetag?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14767516/