【问题标题】:how to use custom django templatetag with django template if statement?如何将自定义 django templatetag 与 django 模板 if 语句一起使用?
【发布时间】:2013-01-23 22:05:39
【问题描述】:

我制作了一个 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 的情况下,才向用户显示一些代码(包括变量本身中的数字)。 谢谢。

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    最简单的方法是使用分配标签..

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

    【讨论】:

    • 自 1.9 版起已弃用:“simple_tag 现在可以将结果存储在模板变量中,应改为使用。”
    【解决方案2】:

    您可以使用 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 %}
    

    【讨论】:

      猜你喜欢
      • 2019-08-07
      • 1970-01-01
      • 2020-08-09
      • 2013-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-25
      相关资源
      最近更新 更多