下面是我的input.yaml
和template.jinja
:
input.yaml:
animals:
my_pets:
- species:
name: "cat"
age: "28"
- species:
name: "dog"
age: "10"
template.jinja
{%- for pet in animals.my_pets %}
Type: {{ pet.species.name }}
Name: {{ pet.species.age }}
{%- endfor %}
结果应该类似于input.yaml
animals:
my_pets:
- species:
name: "cat"
age: "28"
- species:
name: "dog"
age: "10"
可以肯定的是,我的模板上有些东西是不对的,因为它没有呈现预期的结构,但我没有找到什么。
我做了一些修改,不知何故它工作,但不是预期的。
new_input.yaml:
my_pets:
- species:
- name: "cat"
- age: "28"
- species:
- name: "dog"
- age: "10"
new_template.jinja:
my_pets:
{%- for intf in my_pets %}
{%- for i in intf.species %}
{%- for key,value in i.items() %}
- species:
- {{ key }}: "{{ value }}"
{%- endfor %}
{%- endfor %}
{%- endfor %}
new_output像这样:
my_pets:
- species:
- name: "cat"
- species:
- age: "28"
- species:
- name: "dog"
- species:
- age: "10"
但是应该是这样的:
animals:
my_pets:
- species:
name: "cat"
age: "28"
- species:
name: "dog"
age: "10"
在如下循环中:
{%- for key,value in dict.items() %}
{%- endfor %}
您正在做的是循环字典的不同属性—在您的示例中是name
和age
,因此:
- 你不应该用
-
开始你的行,否则你会创建一个列表:{%- for key,value in dict.items() %} {{ key }}: "{{ value }}" {%- endfor %}
- 循环将迭代字典的每个属性,所以,你的父属性
species
应该在循环的顶部,而不是在里面:- species: {%- for key,value in dict.items() %} {{ key }}: "{{ value }}" {%- endfor %}
给定您的输入,此循环将重新创建与输入相同的字典列表:
my_pets:
{%- for pet in animals.my_pets %}
- species:
{%- for key, value in pet.species.items() %}
{{ key }}: "{{ value }}"
{%- endfor %}
{%- endfor %}