在jinja2模板中获取列表的长度。

时间:2022-03-20 20:46:28

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

如何在jinja2模板中获取列表中的元素数量?

For example, in Python:

例如,在Python中:

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

and in jinja2

而在jinja2

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

2 个解决方案

#1


339  

<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:

这里记录了jinja2的内置过滤器;具体地说,正如您已经发现的,长度(及其同义词计数)被记录为:

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")

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

#2


4  

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.

Alex的评论看起来不错,但我还是对使用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 %}

#1


339  

<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:

这里记录了jinja2的内置过滤器;具体地说,正如您已经发现的,长度(及其同义词计数)被记录为:

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")

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

#2


4  

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.

Alex的评论看起来不错,但我还是对使用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 %}