如何使用 jinja2 过滤器过滤掉空列表?

How to filter out empty list using jinja2 filters?

假设我有一个 yml 格式的数据:

 testdata:
     - name: others
       marks: 
         - subject: physics
           marks: 60

     - name: midterm
       marks: []

     - name: final
       marks:
         - subject: math
           mark: 70
         - subject: chemistry
           mark: 80

我需要的是

  1. 拒绝空列表[]
  2. 然后获取所有标记的列表,例如

期望的输出:

[ 
 { subject: physics
   marks: 60
 },
 { subject: math
   mark: 70
 },
 { subject: chemistry
   mark: 80
  }
]

请帮帮我

您可以使用 map and sum 个过滤器

{{ testdata|map(attribute='marks')|sum(start=[]) }}

或仅使用 sum(对于 Jinja >= 2.6)

{{ testdata|sum(attribute='marks', start=[]) }}