I have a long Jinja2 template which has many nested if
/for
statements. It's very hard to read. I would like to indent the {% %}
bits, to make it clearer.
However if I do that, the contents of those blocks gets indented further too.
How can I indent just the {% %}
bits?
I'm using Ansible.
Steps to reproduce:
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
Run with ansible-playbook playbook.yaml
Desired Output
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
Actual behavior:
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
Workaround
If I unindent the if
statements like:
{% for x in range(3) %}
Key{{ x }}:
# The following should be one list
- always here
{% if x % 2 %}
- sometimes here
{% endif %}
{% endfor %}
Then I get the output I want. But the problem is that this is hard to read. (In my actual template, I have if statements inside for inside if, etc. Highly nested.)