我在 Django 模板中有一个列表。我只想在列表的大小大于零的情况下执行某些操作。
我试过 myList|length和 myList|length_is,但都不成功。
myList|length
myList|length_is
我到处都找过了,没有看到任何例子。我怎么检查这个?
如果一个列表没有元素,那么它就被认为是 False,所以你可以这样做:
False
{% if mylist %} <p>I have a list!</p> {% else %} <p>I don't have a list!</p> {% endif %}
参见 https://docs.djangoproject.com/en/stable/ref/templates/builtins/#if: 只是用来复制他们的例子:
{% if athlete_list %} Number of athletes: \{\{ athlete_list|length }} {% else %} No athletes. {% endif %}
如果您正在使用最近的 Django,变更表9530引入了一个{% 空% }块,允许您编写
{% for athlete in athlete_list %} ... {% empty %} No athletes {% endfor %}
当您想要做的事情涉及到对可能为空的列表的特殊处理时,这种方法非常有用。
如果尝试了 myList | length 和 myList | length _ is,但没有得到所需的结果,那么应该使用 myList.count
myList.count
你可以试试:
{% if theList.object_list.count > 0 %} blah, blah... {% else %} blah, blah.... {% endif %}
收集,不要括号
{% if request.user.is_authenticated %} \{\{wishlists.count}} {% else %}0{% endif %}
我需要集合长度来决定我是否应该呈现表 <thead></thead>
<thead></thead>
但不知道为什么 @ 姜戈2.1.7选择的答案会失败(空)我的 forloop之后。
forloop
我得用 {% if forloop.first %} {% endif %}来克服:
{% if forloop.first %} {% endif %}
<table> {% for record in service_list %} {% if forloop.first %} <thead> <tr> <th>日期</th> </tr> </thead> {% endif %} <tbody> <tr> <td>\{\{ record.date }}</td> </tr> {% endfor %} </tbody> </table>
这种方法是有效的:
{% if myList|length %} Do something! {% endif %}
为什么这里有这么多的答案,为什么有这么多的困惑是,这并不总是工作。我认为模板过滤器一度不能用于 if语句的参数,这是后来添加的。现在也可以执行诸如 {% if myList|length >= 3 %}之类的操作。该过滤器应该等效于 len(myList),因此任何类型的对象都可以处理,也可以处理 |length过滤器。
if
{% if myList|length >= 3 %}
len(myList)
|length