获取 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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您还可以在表达式中使用此语法,例如
此处记录了 jinja2 的内置过滤器;具体来说,正如您已经发现的,
length
(及其同义词count
)被记录为:因此,正如您所发现的,模板中的
{{products|count}}
(或等效的{{products|length}}
)将给出“数量产品”(“列表长度”)You can also use this syntax in expressions like
jinja2's builtin filters are documented here; and specifically, as you've already found,
length
(and its synonymcount
) is documented to:So, again as you've found,
{{products|count}}
(or equivalently{{products|length}}
) in your template will give the "number of products" ("length of list")亚历克斯的评论看起来不错,但我仍然对使用范围感到困惑。
在使用范围内的长度处理条件时,以下内容对我有用。
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.
我遇到过长度为 None 的问题,这会导致内部服务器错误: TypeError: object of type 'NoneType' has no len()
我的解决方法是如果对象为 None 则显示 0 并计算其他类型的长度,例如列表就我而言:
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:
如果使用带有数组的 for 循环,则可以使用以下内容
If for loop with array is used then you can use the following
尝试一下:
Try it: