Python jinja2 缩进和空格问题

Python jinja2 indentention and whitespace issue

我有以下 jinja2 模板。当我渲染它时,"endif" 语句之后的行没有正确的缩进。我试过通过 trim_blocks=True 和 keep_trailing_newline=False 但没有成功。

   applications:
      {{ application_name }}:
        version: {{ version }}
        {% if dependencies is not none: -%}
        dependencies:
          {% for key, value in dependencies.items() -%}
            - {{ key }}: {{ value }}
          {% endfor -%}
        {% endif -%}
        {% if departments is not none: -%}
        departments:
          {% for key, value in departments.items() -%}
            - {{ key }}: {{ value }}
          {% endfor -%}
        {% endif -%}
        paid: "yes"
        obsolete: "no"

实际结果。 部门付费块不遵循数据结构层次结构

applications:
  appication1:
    version: "1.0"
    dependencies:
      - database: mysql
      - storage: nfs
      departments: <- Indent is not correct
      - accounting: payroll
      paid: "yes" <- Indent is not correct
    obsolete: "no"

预期结果。 departmentspaidpaidversion 等保持一致.

applications:
  appication1:
    version: "1.0"
    dependencies:
      - database: mysql
      - storage: nfs
    departments:
      - accounting: payroll
    paid: "yes"
    obsolete: "no"

我想知道我还缺少什么。

谢谢,

-%} 会吃掉所有 之后的空格(包括换行符)。我认为您可能希望在左括号 ({%-) 上使用 -:

   applications:
      {{ application_name }}:
        version: {{ version }}
        {% if dependencies is not none: -%}
        dependencies:
          {% for key, value in dependencies.items() -%}
            - {{ key }}: {{ value }}
          {% endfor -%}
        {% endif -%}
        {%- if departments is not none: %}
        departments:
          {% for key, value in departments.items() -%}
            - {{ key }}: {{ value }}
          {% endfor -%}
        {%- endif %}
        paid: "yes"
        obsolete: "no"

我最终是这样解决的:

{%- if environment is not none: %}
enviroment:
{%- for key, value in environment.items() %}
  - {{ key }}: {{ value }}
{%- endfor -%}
{%- endif %}