获取Jinja2模板中列表的长度

问题:获取Jinja2模板中列表的长度

如何获得jinja2模板中列表中的元素数?

例如,在Python中:

print(template.render(products=[???]))

和在jinja2

<span>You have {{what goes here?}} products</span>

How do I get the number of elements in a list in jinja2 template?

For example, in Python:

print(template.render(products=[???]))

and in jinja2

<span>You have {{what goes here?}} products</span>

回答 0

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

您也可以在以下表达式中使用此语法

{% if products|length > 1 %}

jinja2的内置过滤器记录在这里;具体来说,正如您已经发现的length(及其同义词count)记录为:

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

因此,正如您所发现的,模板中的{{products|count}}(或等效{{products|length}})将给出“产品数量”(“列表长度”)

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

You can also use this syntax in expressions like

{% if products|length > 1 %}

jinja2’s builtin filters are documented here; and specifically, as you’ve already found, length (and its synonym count) is documented to:

Return the number of items of a sequence or mapping.

So, again as you’ve found, {{products|count}} (or equivalently {{products|length}}) in your template will give the “number of products” (“length of list”)


回答 1

亚历克斯的评论看起来不错,但我仍然对使用范围感到困惑。在使用长度范围内的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 %}

Alex’ comment looks good but I was still confused with using range. The following worked for me while working on a for condition using length within range.

{% 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 %}

回答 2

我遇到了长度为None的问题,这导致内部服务器错误:TypeError:类型为’NoneType’的对象没有len()

我的解决方法是,如果object为None,则仅显示0并计算其他类型的长度,例如我的列表:

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

I’ve experienced a problem with length of None, which leads to Internal Server Error: TypeError: object of type ‘NoneType’ has no len()

My workaround is just displaying 0 if object is None and calculate length of other types, like list in my case:

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