Yaml 如何修复Jinja2 yml缩进

Yaml 如何修复Jinja2 yml缩进,yaml,jinja2,indentation,Yaml,Jinja2,Indentation,我有下面的yml格式的数据源结构 systemEmailAccount: mode: DEFAULT username: test@gmail.com password: Test#123 displayName: "Test" senderAddress: test@gmail.com oauthClientId: "xxxxxxx" oauthSecret: "xxxxxxxxx"

我有下面的yml格式的数据源结构

  systemEmailAccount:
   mode: DEFAULT
   username: test@gmail.com
   password: Test#123
   displayName: "Test"
   senderAddress: test@gmail.com
   oauthClientId: "xxxxxxx"
   oauthSecret: "xxxxxxxxx"
   tokenExpires: 1458168133864
  secondarySystemEmailAccount:
   mode: DEFAULT
   username: test2@gmail.com
   password: Test#123
   displayName: "Test2"
   senderAddress: test2@gmail.com
   oauthClientId: "xxxxxxx"
   oauthSecret: "xxxxxxxxx"
   tokenExpires: 14581681338777
我正在尝试使用这个jinja2模板片段将其重新生成为一个新文件

     systemEmailAccount:
     {% for key,value in config.systemEmailAccount.items() %}
     {% if key == "mode" or key == "username" or key == "password" or key == "senderAddress" or key == "tokenExpires" %}
     {{ key }}: {{ value }}
     {% else %}
     {{ key }}: {{ '"' }}{{ value }}{{ '"' }}
     {% endif %}
     {% endfor %}
     secondarySystemEmailAccount:
     {% for key,value in config.secondarySystemEmailAccount.items() %}
     {% if key == "mode" or key == "username" or key == "password" or key == "senderAddress" or key == "tokenExpires" %}
     {{ key }}: {{ value }}
     {% else %}
     {{ key }}: {{ '"' }}{{ value }}{{ '"' }}
     {% endif %}
     {% endfor %}
但是缩进在输出中似乎不正确

    emailAccount1:
        username: test@gmail.com
            mode: DEFAULT
            password: Test#123
            displayName: "Test"
            senderAddress: test@gmail.com
            oauthClientId: "xxxxxxx"
            oauthSecret: "xxxxxxxxx"
            tokenExpires: 1458168133864
        emailAccount2:
        username: test2@gmail.com
            mode: DEFAULT
            password: Test#123
            displayName: "Test2"
            senderAddress: test2@gmail.com
            oauthClientId: "xxxxxxx"
            oauthSecret: "xxxxxxxxx"
            tokenExpires: 1458168133864

有没有解决这个问题的建议?

看看官方
jinja2
文档中的这两个主题

  • 空白控制
  • 过滤器缩进
请尝试以下代码段:

systemEmailAccount:
{%- for key,value in config.systemEmailAccount.items() %}

  {%- if key == "mode" or key == "username" or key == "password" or key == "senderAddress" or key == "tokenExpires" %}

{%- filter indent(width=2) %}
{{ key }}: {{ value }}
{%- endfilter %}

  {%- else %}

{%- filter indent(width=2) %}
{{ key }}: {{ '"' }}{{ value }}{{ '"' }}
{%- endfilter %}

  {%- endif %}

{%- endfor %}

[..]

你问题中的缩进正确吗?因为我看不出您显示的模板会如何导致输出中的缩进。@larsks是的,我在数据源中提到了它,因为使用示例数据和模板,我得到的输出与您显示的输出不一样。这让我怀疑:(a)问题本身存在格式错误,或者(b)此处没有足够的信息重现问题。