【问题标题】:Nested traversal of yaml using jinja2 template使用jinja2模板嵌套遍历yaml
【发布时间】:2023-03-14 09:42:01
【问题描述】:

a.yaml

Adir:
   test1:
    - param1
    - param2
Bdir:  
  test2:
    - param3
    - param4

Python 代码 (py3)

from ruamel.yaml import YAML
from jinja2 import Environment, FileSystemLoader

if __name__ == "__main__":
    yaml = YAML(typ='safe')
    file = './a.yaml'
    ydata = yaml.load(open(file))
    env = Environment(loader=FileSystemLoader("templatedir"), trim_blocks=True, lstrip_blocks=True)
    gettmp = env.get_template('template.j2')
    test = gettmp.render(dict=ydata)

模板.j2

 {% for dir in dict %}
 {% for test, value in dir.items() %}
 {{ dir }} - {{ test }} - {{ value }}
 {% endfor %}
 {% endfor %}

我收到以下错误:

jinja2.exceptions.UndefinedError: 'str object' has no attribute 'items'

我在这里遗漏了什么吗?使用 jinja2 导入模板中的 item() 方法应该可以工作

【问题讨论】:

    标签: python python-3.x jinja2


    【解决方案1】:

    这是我的问题的解决方案:

    模板.j2

     {% for dir,tests in dict.items() %}
     {% for test, value in tests.items() %}
     {{ dir }} - {{ test }} - {{ value }}
     {% endfor %}
     {% endfor %}
    

    输出是:

     Adir - test1 - ['param1', 'param2']
     Bdir - test2 - ['param3', 'param4']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-27
      • 1970-01-01
      • 1970-01-01
      • 2011-09-06
      • 2016-07-18
      • 2019-01-16
      • 2017-05-15
      • 2015-02-27
      相关资源
      最近更新 更多