jinja2 - 在未定义变量时去掉空行

jinja2 - get rid of empty lines when variables are not defined

在以下示例中,当未定义变量时,我总是得到一个换行符:

剧本:

- name: testplaybook jinja2
  hosts: all
  gather_facts: no
  vars:
    testvalue1: "A"
    testvalue2: "B"
    testvalue4: "D"
    testvalue5: "E"

  tasks:

    - name: test jinja2 template
      local_action:
        module: template
        src: testtemplate2.xml.j2
        dest: testtemplate2_output.xml
        trim_blocks: no

testtemplate2.xml.j2:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <instances>
    <testinstance staticvaluex=X
      staticvaluey=Y
      staticvaluez=Z
{% if testvalue1 is defined %}      value1="{{ testvalue1 }}"{% endif %}
{% if testvalue2 is defined %}      value2="{{ testvalue2 }}"{% endif %}
{% if testvalue3 is defined %}      value3="{{ testvalue3 }}"{% endif %}
{% if testvalue4 is defined %}      value4="{{ testvalue4 }}"{% endif %}
{% if testvalue5 is defined %}      value5="{{ testvalue5 }}"{% endif %}
    />
  </instances>
</configuration>

在示例中,我们没有指定 testvalue3,因此输出 testtemplate2_output.xml 包含换行符:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <instances>
    <testinstance staticvaluex=X
      staticvaluey=Y
      staticvaluez=Z
      value1="A"
      value2="B"

      value4="D"
      value5="E"
    />
  </instances>
</configuration>

我怎样才能摆脱这条新线?

我用 {%-+%}trim_blocks 等尝试了很多,但似乎没有任何效果。 当然,这应该适用于这些行中的任何一行,因为这些变量中的任何一个都可以为空并且不能有换行符。

将这个 j2 与这个剧本一起使用可以完成工作:

  tasks:
    - name: test jinja2 template
      local_action:
        module: template
        src: testtemplate2.xml.j2
        dest: testtemplate2_output.xml

文件 j2

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <instances>
    <testinstance staticvaluex=X
      staticvaluey=Y
      staticvaluez=Z
{%- if testvalue1 is defined %}      
      value1="{{ testvalue1 }}"
{% else %}

{% endif %}
{% if testvalue2 is defined %}
      value2="{{ testvalue2 }}"
{% endif %}
{% if testvalue3 is defined %}
      value3="{{ testvalue3 }}"
{% endif %}
{% if testvalue4 is defined %}
      value4="{{ testvalue4 }}"
{% endif %}
{% if testvalue5 is defined %}
      value5="{{ testvalue5 }}"
{% endif %}
    />
  </instances>
</configuration>

结果:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <instances>
    <testinstance staticvaluex=X
      staticvaluey=Y
      staticvaluez=Z      
      value1="A"
      value2="B"
      value4="D"
      value5="E"
    />
  </instances>
</configuration>