简体   繁体   中英

Get count of list items that meet a condition with Jinja2

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

There is a list filter that will transform a generator into a list. So:

{{ my_list|selectattr('foo')|list|length }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM