Python jinja2 indentention和whitespace问题

时间:2016-11-22 00:49:12

标签: python templates jinja2

我有以下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"

预期结果。 部门付费付费版本等对齐。

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

我想知道还有什么我可以错过。

谢谢,

2 个答案:

答案 0 :(得分:0)

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

   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"

答案 1 :(得分:0)

这是我如何最终解决它:

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