如何将自定义 django templatetag 与 django template if 语句一起使用?

2024-04-10

我制作了一个 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 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 %}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将自定义 django templatetag 与 django template if 语句一起使用? 的相关文章

随机推荐