3_2-jinja2_for_if

---
- hosts: serverf
  vars:
    persons:
      user1:
        name: demon
        age: 12
      user2:
        name: student
        age: 20
  tasks:
    - name: print message
      debug:
        msg: |
          {% for item in persons: -%}
            {{ item }}
          {%- endfor %}
# 直接遍历 vars 打印输出的是 key---user1 & user2 ,
    - name: print message persons
      debug:
        msg: |
          {% for itemkey,itemvalue in persons.items(): -%}
            {% if itemvalue.age | int > 18 -%}
            my name is {{ itemvalue.name }}, my age is {{ itemvalue.age }}
            {%- endif %} 
          {%- endfor %}
# 字典格式可以使用 Python 语法---persons.items()
# 自定义变量名称---itemkey & itemvalue
# 键,冒号之【前】的字符串---itemkey
# 值,冒号之【后】的字符串---itemvalue
# itemkey: itemvalue == name:demon
posted @ 2022-08-03 22:53  Demon丶安梓  阅读(14)  评论(0编辑  收藏  举报