在jinja2模板中获取列表长度

460
如何在jinja2模板中获取列表中的元素数量?
例如,在Python中:
print(template.render(products=[???]))

而在jinja2中

<span>You have {{what goes here?}} products</span>
5个回答

809
<span>You have {{products|length}} products</span>

你也可以在表达式中使用这种语法

{% if products|length > 1 %}

jinja2的内置过滤器在这里有详细说明;并且特别地,如你已经发现的那样,length(以及它的同义词count)的文档描述如下:

返回序列或映射的项目数。

因此,就像你已经发现的那样,在您的模板中使用{{products|count}}(或等效的{{products|length}})将给出“产品数量”(“列表长度”)


1
我们能否也检查未定义?我必须使用 {% if products is none ... %},这很烦人。 - Nam G VU
3
@wvxvw 这个确实可以用:{% set item_count = items | length %},只要 items 是一个列表、字典等。 - kbolino
感谢@AlexMartelli。此外,我们还可以使用内联语法,例如 {{ form.select_field(size=5 if form.select_field.choices|count > 5 else form.select_field.choices|count) }} - Filipe Bezerra de Sousa

16

Alex的评论看起来很好,但我还是对使用range感到困惑。 在使用长度为范围的for条件下,以下代码对我有效。

{% for i in range(0,(nums['list_users_response']['list_users_result']['users'])| length) %}
<li>    {{ nums['list_users_response']['list_users_result']['users'][i]['user_name'] }} </li>
{% endfor %}

1
你可以用Pythonic的方式循环遍历你的集合:{% for user in nums['list_users_response']['list_users_result']['users'] %} <li>{{ user['user_name'] }} </li> {% endfor %} - dmitry_romanov

6

我曾经遇到过一个None长度的问题,导致了内部服务器错误:TypeError: object of type 'NoneType' has no len()。

我的解决方法是,如果对象是None,则显示0,并计算其他类型的长度,比如在我的情况下是list:

{{'0' if linked_contacts == None else linked_contacts|length}}

3
你可以使用 none 内置函数来测试 _None_。点击这里查看更多信息:https://jinja.palletsprojects.com/en/2.10.x/templates/#none。此线程上有示例:https://dev59.com/l2Ik5IYBdhLWcg3wE6d8。 - Wojciech Jakubas

5
如果使用数组的 for 循环,可以使用以下代码:
{% for i in range(array|length) %}
          array[i]
{% endfor %}

0
试一下:
<span>You have {% for n in products %}{% if loop.index == 1 %}{{ loop.length }}{% endif %}{% endfor %} products</span>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接