获取Jinja2模板中列表的长度 [英] Get lengths of a list in a jinja2 template

查看:126
本文介绍了获取Jinja2模板中列表的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例如,在Python中:

For example, in Python:

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

和jinja2

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

推荐答案

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

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

You can also use this syntax in expressions like

{% if products|length > 1 %}

此处中记录了Jinja2的内置过滤器;具体来说,正如您已经发现的, length (及其同义词count)记录到:

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.

因此,再次如您所见,模板中的{{products|count}}(或等效的{{products|length}})将给出产品数量"(列表长度")

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

这篇关于获取Jinja2模板中列表的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆