我有一个很长的Jinja2模板,其中包含许多嵌套的if
/ for
语句。很难读。我想缩进{% %}
位,以使其更清楚。
但是,如果我这样做,这些块的内容也会缩进更多的地方。
如何缩进{% %}
位的 just ?
我正在使用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语句,等等。高度嵌套。)
答案 0 :(得分:4)
问:如何在jinja2中缩进嵌套的if / for语句?
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 %}