【问题标题】:Python jinja2 indentention and whitespace issuePython jinja2 缩进和空格问题
【发布时间】:2016-11-22 00:49:12
【问题描述】:

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

实际结果。 departmentspaid 块不遵循数据结构层次结构

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"

我想知道我还缺少什么。

谢谢,

【问题讨论】:

    标签: python templates jinja2


    【解决方案1】:

    这就是我最终解决它的方法:

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

    【讨论】:

      【解决方案2】:

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

         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: %} environment: {%- for key, value in environment.items() %} - {{ key }}: {{ value }} {%- endfor -%} {% - endif %}`
      猜你喜欢
      • 2017-02-04
      • 1970-01-01
      • 1970-01-01
      • 2018-01-06
      • 1970-01-01
      • 2011-01-03
      • 2014-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多