使用 Jinja2 获取满足条件的列表项数 [英] Get count of list items that meet a condition with Jinja2
本文介绍了使用 Jinja2 获取满足条件的列表项数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字典列表,其中每个字典都有一个布尔条目.我想显示 True
的项目,以及这些项目的数量.我正在使用 selectattr
过滤器,但它返回一个生成器,并在其上调用 |length
会引发错误.如何获取 Jinja 中 selectattr
返回的项目长度?
I have a list of dictionaries where each dict has a boolean entry. I want to display the items that are True
, along with the count of those items. I'm using the selectattr
filter, but it returns a generator, and calling |length
on it raise an error. How can I get the length of the items returned from selectattr
in Jinja?
my_list = [{foo=False, ...}, {foo=True, ...}, ...]
{{ my_list|selectattr('foo', 'equalto', True)|length }}
推荐答案
有一个 list
过滤器,可以将生成器转换为列表.所以:
There is a list
filter that will transform a generator into a list. So:
{{ my_list|selectattr('foo')|list|length }}
这篇关于使用 Jinja2 获取满足条件的列表项数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文