[英]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语句,等等。高度嵌套。)
问: 如何在jinja2中缩进嵌套的if / for语句?
答:关闭默认的微调和手动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 %}
请参见空白控件 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.