Jinja2 检查列表是否为空

Jinja2 check if lsit empty

下面是我的样本变量

我的列表的示例输入是 vars.yml

my_list
  - { studInfo: [], studName: "Jack" }
  - { studInfo: [{'name':'John','id','123'},{'name':'Jack','id','112'}], studName: "Aaron" }

我能知道如何查看列表是否为空我在下面尝试过我得到 2

student.xml.j2

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

我的剧本如下

- template:
    src: "{{ role_path }}/tasks/student..xml.j2"
    dest: "{{path }}/{{ item.studName }}.xml"
  loop: "{{ my_list}}"

输出预期 Jack.xml

list length is 0

Aaron.xml

list length is 2

我认为你差不多就在那里,但你并没有在你的问题中真正说明实际问题是什么。虽然您的 my_list var 是 'technically' 有效的,但它伤害了我的眼睛,所以我在下面的示例中将其转换为纯传统的 YAML :)(我也使用您的确切语法进行了测试,以确认它不是引入任何问题)

我认为你的根本问题是 trim 的使用。这个过滤器需要一个字符串,而不是一个列表,因此在这里没有意义。查看此示例剧本:

- hosts: localhost
  connection: local
  vars:
    my_list:
      - studInfo: [] 
        studName: Jack
      - studInfo:
        - name: John
          id: 123
        - name: Jack
          id: 112
        studName: Aaron
  tasks:
    - name: Outputting string showing the count
      debug:
        msg: "{{ item.studName }} list length is {{ item.studInfo | length }}"
      loop: "{{ my_list }}"
    
    - name: Returning a boolean based on whether empty or not
      debug:
        var: item.studInfo | length | ternary(true, false)
      loop: "{{ my_list }}"

这是产生的输出:

PLAY [localhost] ************************************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************
ok: [localhost]

TASK [Outputting string showing the count] **********************************************************************************
ok: [localhost] => (item={'studInfo': [], 'studName': 'Jack'}) => {
    "msg": "Jack list length is 0"
}
ok: [localhost] => (item={'studInfo': [{'name': 'John', 'id': 123}, {'name': 'Jack', 'id': 112}], 'studName': 'Aaron'}) => {
    "msg": "Aaron list length is 2"
}

TASK [Returning a boolean based on whether empty or not] ********************************************************************
ok: [localhost] => (item={'studInfo': [], 'studName': 'Jack'}) => {
    "ansible_loop_var": "item",
    "item": {
        "studInfo": [],
        "studName": "Jack"
    },
    "item.studInfo | length | ternary(true, false)": false
}
ok: [localhost] => (item={'studInfo': [{'name': 'John', 'id': 123}, {'name': 'Jack', 'id': 112}], 'studName': 'Aaron'}) => {
    "ansible_loop_var": "item",
    "item": {
        "studInfo": [
            {
                "id": 123,
                "name": "John"
            },
            {
                "id": 112,
                "name": "Jack"
            }
        ],
        "studName": "Aaron"
    },
    "item.studInfo | length | ternary(true, false)": true
}