如何在 jinja2 中缩进嵌套的 if/for 语句

2024-05-07

我有一个很长的 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 语句,等等。高度嵌套。)


Q: “如何在 Jinja2 中缩进嵌套的 if/for 语句?”

A:关闭默认修剪并手动ltrim仅缩进控制语句{%-。例如,下面的模板可以满足您的需求

shell> cat templates/template.j2
#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 %}

The task

    - template:
        src: template.j2
        dest: template.yaml

创建文件模板.yaml

shell> cat template.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

See 空白控制 https://jinja.palletsprojects.com/en/latest/templates/#whitespace-control.


Notes

  1. 中的破折号{%- endfor %}删除键之间的空行。

  2. 默认参数trim_blocks: yes. See template https://docs.ansible.com/ansible/latest/collections/ansible/builtin/template_module.html#template-template-a-file-out-to-a-remote-server.

  3. 文档部分空白控制 https://jinja.palletsprojects.com/en/latest/templates/#whitespace-control says:

您可以通过在块末尾添加加号 (+) 来手动禁用 trim_blocks 行为

然后,以下模板给出相同的结果

shell> cat templates/template.j2
{% for x in range(3) %}
Key{{ x }}:
  # The following should be one list
  - always here
  {%- if x % 2 +%}
  - sometimes here
  {%- endif +%}
{% endfor %}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 jinja2 中缩进嵌套的 if/for 语句 的相关文章

随机推荐