You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible模板中如何使用Jinja2检查列表是否为空(附示例)

Correctly Calculate Empty List Length in Ansible Jinja2 Templates

Let's break down what's going wrong here and fix it:

Your current approach uses trim|length on the studInfo list, but that's the root of the issue. The trim filter is designed for strings—it removes leading/trailing whitespace from text. When you apply it to a list, Jinja2 converts the list to a string first:

  • An empty list [] becomes the string "[]", which after trimming is still "[]"—so length returns 2 instead of 0.
  • A non-empty list like [{'name':'John','id':'123'},{'name':'Jack','id':'112'}] gets converted to a longer string, and trim does nothing useful here either.

The Fix: Use length Directly on the List

Jinja2's length filter works natively on lists—it returns the number of elements, including 0 for empty lists. Just remove the trim filter entirely:

list length is {{ item.studInfo | length }}

This will give you exactly what you want:

  • For Jack's entry (empty studInfo), it outputs list length is 0
  • For Aaron's entry (2 elements in studInfo), it outputs list length is 2

Bonus: Adding Empty List Checks (If Needed)

If you want to add custom messaging for empty lists, you can use a Jinja2 conditional:

{% if item.studInfo | length == 0 %}
list length is 0 (no student info available)
{% else %}
list length is {{ item.studInfo | length }}
{% endif %}

Or use the ternary filter for a more concise one-liner:

list length is {{ item.studInfo | length | ternary(item.studInfo | length, "0 (empty)") }}

Your Ansible playbook loop configuration is already correct—no changes needed there.

内容的提问来源于stack exchange,提问作者josh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 19:52:49