Jinja2 为 yaml 导入中存在的项目返回空字符串

Jinja2 returning empty string for item that exists from yaml import

我引入了 yaml 并使用它来填充一些 jinja 模板,我已经将所有内容简化到下面的这个演示中,复制粘贴它应该 运行。 Jinja 没有找到 a['ports']['b']['vmtype'] 对象,即使它们在 python 调试中看起来是一个非常好的字典。

Python

    from jinja2 import Template
    from yaml import safe_load
    
    with open('demo.jinja', 'r') as templatefile:
        template = Template(templatefile.read())
    
    with open("demo.yaml", 'r') as stream:
        configs = safe_load(stream)
    
    for config in configs:
        output = template.render(configs[config])
        print(output)

YAML

---
  a:
    name: foo
    example: helloworld
    ports:
      a:
      b:
        vmtype: aa
      c:
        vmtype: bb
      d:
        vmtype: cc

金贾


{{ name }}
Things
{% for port in ports %}
    {% if 'vmtype' in port %}
    this worked "{{ port }}"
    this worked "{{ port.vmtype }}"
    {%- else -%}
    this didn't work "{{  port  }}"
    this didn't work "{{  port.vmtype  }}"
    {%- endif -%}
{% endfor %}
end things
{{ example }}

这只输出循环中所有端口对象的 this didn't work 行,它们不包含 vmtype 字符串。

使用的库:PyYaml 和 Jinja2

你的端口配置是字典

你需要像这样遍历它

{{ name }}
Things
{% for port, data in ports.items() %}
    {% if data.vmtype %}
      this worked "{{ port }}"
      this worked "{{ data.vmtype }}"
    {% else %}
      this didn't work "{{  port  }}"
      this didn't work "{{  data.vmtype  }}"
    {% endif %}
{% endfor %}
end things
{{ example }}

Reference https://jinja.palletsprojects.com/en/3.0.x/templates/#list-of-control-structures