我有一个很长的 Jinja2 模板,其中有很多嵌套if
/for
声明。很难读。我想缩进{% %}
位,使其更清晰。
但是,如果我这样做,这些块的内容也会进一步缩进。
我怎样才能缩进just the {% %}
bits?
我正在使用安塞布尔。
重现步骤:
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 语句,等等。高度嵌套。)