Jinja2读取已存在的YAML字典字段返回空字符串问题求助
问题根因
你配置中的ports字段是字典结构,Jinja2默认遍历字典时只会返回字典的键(也就是字符串a/b/c/d),而非键对应的配置值。你当前写的'vmtype' in port是判断字符串中是否包含vmtype子串,永远返回False,因此所有循环都会走else分支。
另外你配置中ports.a没有赋值,PyYAML加载后会解析为None,要注意空值判断避免报错。
解决方案
修改Jinja模板的遍历逻辑,遍历字典的values()获取每个端口对应的配置字典即可:
{{ name }} Things {% for port in ports.values() %} {% if port is mapping and 'vmtype' in port %} this worked "{{ port }}" this worked "{{ port.vmtype }}" {%- else -%} this didn't work "{{ port }}" {%- endif -%} {% endfor %} end things {{ example }}
如果需要同时拿到端口名(即a/b/c/d),可以遍历字典的items():
{% for port_name, port_config in ports.items() %} 端口名:{{ port_name }} {% if port_config is mapping and 'vmtype' in port_config %} vmtype值:{{ port_config.vmtype }} {% else %} 该端口无有效vmtype配置 {% endif %} {% endfor %}
修改后重新运行即可正常读取vmtype字段。
内容的提问来源于stack exchange,提问作者Preston
相关产品推荐
相关产品推荐

