繁体   English   中英

如何在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语句,等等。高度嵌套。)

问: 如何在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 %}

请参见空白控件


笔记

  • {%-endfor%}中的破折号删除了键之间的空行。
  • 默认情况下,参数“ trim_blocks:yes” 参见模板

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM