2016-04-26 62 views
1

我試圖用jinja2輸出一個嵌套字典到yaml文件。但是我不確定如何訪問嵌套的字典。 對於數據,我可以使用下面的平坦字典。jinja 2 nested dictionaries to yaml

- request: 
     path: {{ path }} 
     headers: 
      origin: 'somedomain.com' 
      user-agent: 'agent' 
      referer: 'some.domain.com' 
      authority: 'somedomain.com' 
     data: 
      {% for key, value in data.items() -%} 
      {{ key }}: '{{ value }}' 
      {%- endfor %} 
     response: 
     content: 
      file: {{ content }} 

但是,像下面的嵌套字典,我如何實現在底部的輸出?

{'toplevelkey1': {'nestedkey1': 'value1', 'nestedkey2': 123, 'nestedkey3': '55', 
       'nestedkey4': 1560}, 'toplevelkey34': 'df', 
'toplevelkey2': {'somekey12': 68, 'somekey58': False, 'somekey48': 3, 'somekey38': 'ADF', 
           'somekey39': 'St'}, 'toplevel34': 'T', 
'toplevel8': {'key33': 68, 'key94': 3, 'key83': 'T', 'key84': 'dog'}} 

需要的輸出

- request: 
    path: /some/path 
    headers: 
     origin: 'somedomain.com' 
     user-agent: 'agent' 
     referer: 'somedomain.com' 
     authority: 'somedomain.com' 
    data: 
     toplevelkey1: 
     nestedkey1: 'value1' 
     nestedkey2: '123 
     ....  : .... 
     toplevel34: 'T' 
     toplevelkey2: 
     'somekey12': 68 
     .....  : ..... 
    response: 
    content: 
     file: address.json 
+0

你是對的改變。謝謝。 – Yunti

回答

3

我將引入定製遞歸「漂亮打印」過濾將支持嵌套結構的任何級別:

def pretty(d, indent=10, result=""): 
    for key, value in d.iteritems(): 
     result += " " * indent + str(key) 
     if isinstance(value, dict): 
      result = pretty(value, indent + 2, result + "\n") 
     else: 
      result += ": " + str(value) + "\n" 
    return result 

env.filters['pretty'] = pretty 

而且在使用它模板爲:

{{ data|pretty }}