Sni*_*irD 3 python django django-templates
我制作了一个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())
Run Code Online (Sandbox Code Playgroud)
并且在模板本身内,我想只有当它大于零时才显示给用户,所以我试过:
{% ifnotequal unread_messages_count 0 %}
some code...
{% endifnotequal %}
Run Code Online (Sandbox Code Playgroud)
但显然它没有用.甚至没有'with'声明:
{% with unread_messages_count as unread_count %}
{% ifnotequal unread_count 0 %}
some code...
{% endifnotequal %}
{% endwith %}
Run Code Online (Sandbox Code Playgroud)
如何检查变量是否大于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 %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2863 次 |
| 最近记录: |