如何在 jinja2 中缩进嵌套的 if/for 语句

How to indent nested if/for statements in jinja2

我有一个很长的 Jinja2 模板,其中有许多嵌套的 if/for 语句。很难读。我想缩进 {% %} 位,以使其更清楚。 但是,如果我这样做,这些块的内容也会进一步缩进。

如何缩进 {% %} 位?

我正在使用 Ansible。

重现步骤:

template.yaml.j2

{% for x in range(3) %}
Key{{ x }}:
   # The following should be one list
   - always here
   {% if x % 2 %}
   - sometimes here
   {% endif %}
{% endfor %}

playbook.yaml

---
- hosts: localhost
  connection: local

  tasks:
    - template:
        src: template.j2
        dest: template.yaml

运行 与 ansible-playbook playbook.yaml

期望的输出

Key0:
   # The following should be one list
   - always here
Key1:
   # The following should be one list
   - always here
   - sometimes here
Key2:
   # The following should be one list
   - always here

实际行为:

Key0:
   # The following should be one list
   - always here
   Key1:
   # The following should be one list
   - always here
      - sometimes here
   Key2:
   # The following should be one list
   - always here

解决方法

如果我取消缩进 if 语句,例如:

{% for x in range(3) %}
Key{{ x }}:
   # The following should be one list
   - always here
{% if x % 2 %}
   - sometimes here
{% endif %}
{% endfor %}

然后我得到我想要的输出。 但问题是这很难阅读。 (在我的实际模板中,我在 if 等内部有 if 语句。高度嵌套。)

Q: How to indent nested if/for statements in jinja2?

A:关闭默认修剪并手动 ltrim 仅缩进控制语句 {%-.

例如,下面的模板可以满足您的需求

#jinja2: trim_blocks:False
{% for x in range(3) %}
Key{{ x }}:
   # The following should be one list
   - always here
   {%- if x % 2 %}
   - sometimes here
   {%- endif %}
{%- endfor %}

参见Whitespace Control


笔记

  • {%- endfor %}中的破折号删除了键之间的空行。
  • 默认参数"trim_blocks: yes"。参见 template