2016-11-22 47 views
0

我有以下jinja2模板。當我渲染它時,「endif」語句後面的行沒有正確的縮進。我試過傳遞trim_blocks = True和keep_trailing_newline = False沒有太大的成功。Python jinja2注意和空白問題

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" 

我想知道我可能會錯過什麼。

感謝,

回答

0

這怎麼我終於解決了這個問題:

{%- if environment is not none: %} 
enviroment: 
{%- for key, value in environment.items() %} 
    - {{ key }}: {{ value }} 
{%- endfor -%} 
{%- endif %} 
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" 
+0

謝謝你的提示! '{% - 如果環境不是none:%} 環境: {% - 爲鍵,在environment.items值()%} - {{鍵}}:{{值}} {% - endfor - %} {% - endif%}' –