我在Django模板中的if语句出了什么问题?

时间:2015-03-08 22:37:07

标签: django django-templates

在模板中,我已经介绍了这行代码。

{% if inbox_count == 0 %}No Messages{% else %}New Messages{% endif %}

即使打印inbox_count显示为0,它也会显示“新消息”。

在模板的顶部,我有{%load inbox%}

这是实际的模板标签:

from django.template import Library, Node, TemplateSyntaxError

class InboxOutput(Node):
    def __init__(self, varname=None):
        self.varname = varname

    def render(self, context):
        try:
            user = context['user']
            count = user.received_messages.filter(read_at__isnull=True, recipient_deleted_at__isnull=True).count()
        except (KeyError, AttributeError):
            count = ''
        if self.varname is not None:
            context[self.varname] = count
            return ""
        else:
            return count        

def do_print_inbox_count(parser, token):
    """
    A templatetag to show the unread-count for a logged in user.
    Returns the number of unread messages in the user's inbox.
    Usage::

        {% load inbox %}
        {% inbox_count %}

        {# or assign the value to a variable: #}

        {% inbox_count as my_var %}
        {{ my_var }}

    """
    bits = token.contents.split()
    if len(bits) > 1:
        if len(bits) != 3:
            raise TemplateSyntaxError("inbox_count tag takes either no arguments or exactly two arguments")
        if bits[1] != 'as':
            raise TemplateSyntaxError, "first argument to inbox_count tag must be 'as'"
        return InboxOutput(bits[2])
    else:
        return InboxOutput()

register = Library()     
register.tag('inbox_count', do_print_inbox_count)

这会返回一个字符串吗?

1 个答案:

答案 0 :(得分:0)

您是否尝试过{% if not inbox_count %}

{% if not inbox_count %}No Messages{% else %}New Messages{% endif %}

同时确保inbox_count与运营商=之间以及=与数值0之间的空格。由于此inbox_count=0会导致TemplateSyntaxError

  

无法解析余数:' == 0'来自' inbox_count == 0''

所以代码应该是这样的:

{% if inbox_count == 0 %}No Messages{% else %}New Messages{% endif %}

<强>更新

[...]

def render(self, context):
    count = 0
    try:
        user = context['user']
        count = user.received_messages.filter(read_at__isnull=True, recipient_deleted_at__isnull=True).count()
    except (KeyError, AttributeError):
        pass

    if self.varname is not None:
        context[self.varname] = count

    return count