gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:28:28 31 4
gpt4 key购买 nike

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

最佳答案

Q: How to indent nested if/for statements in jinja2?



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 %}

Whitespace Control .

笔记
  • {%- endfor %} 中的破折号删除键之间的空行。
  • 默认参数“trim_blocks:yes”。见 template .
  • 关于nested - 如何在 jinja2 中缩进嵌套的 if/for 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57864828/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com