如何使用自定义django templatetag与django模板if语句? [英] how to use custom django templatetag with django template if statement?
问题描述
我已经制作了一个django模板标签,可以计算我的一个自定义用户多对多字段长度:
从django导入模板
register = template.Library()
@ register.simple_tag(took_context = True)
def unread_messages_count(context):
user = context ['request']。user
return len(user.messages_unread.all())
并且在模板本身中,只有当它大于零时才想将其显示给用户,所以我尝试:
{%ifnotequal unread_messages_count 0%}
一些代码...
{%endifnotequal%}
但显然它没有工作。甚至没有'with'语句:
{%with unread_messages_count as unread_count%}
{%ifnotequal unread_count 0 %}
一些代码...
{%endifnotequal%}
{%endwith%}
如何检查变量是否大于0,只有当它是,给用户一些代码(包括变量本身的数字)。
谢谢。
最简单的方法是使用赋值标签..
https:// docs.djangoproject.com/en/dev/howto/custom-template-tags/#assignment-tags
@ register.assignment_tag(took_context = True)
pre>
def unread_messages_count(context):
user = context ['request']。user
return len(user.messages_unread.all())
{%unread_messages_count as cnt%}
{%if cnt%}
foo
{%endif%}
I've made a django template tag that counts one of my custom user many-to-many field length:
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())
and within the template itself, I want to show it to user only if it's larger than zero, so I tried:
{% ifnotequal unread_messages_count 0 %} some code... {% endifnotequal %}
but obviously it didn't work. not even with a 'with' statement:
{% with unread_messages_count as unread_count %} {% ifnotequal unread_count 0 %} some code... {% endifnotequal %} {% endwith %}
How can I check that the variable is larger than 0 and only if it is, present some code to the user (including the number in the variable itself). thanks.
解决方案The easiest way would be to use an assignment tag..
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 %}
这篇关于如何使用自定义django templatetag与django模板if语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!