Python 使用jinja2模板中的空白控件修剪块

Python 使用jinja2模板中的空白控件修剪块,python,jinja2,Python,Jinja2,我试图在jinja2 for循环的结果周围打印一行空白,但我就是无法让它工作。有人能告诉我我做错了什么吗 from jinja2 import Template, Environment template = Template("""This is some text that should have a single blank line below it. {% for i in range(10) -%} line {{ i }} {% endfor %} This is some

我试图在jinja2 for循环的结果周围打印一行空白,但我就是无法让它工作。有人能告诉我我做错了什么吗

from jinja2 import Template, Environment

template = Template("""This is some text that should have a single blank line below it.

{% for i in range(10) -%}
line {{ i }}
{% endfor %}

This is some text that should have a single blank line above it.""")

template.environment = Environment(trim_blocks=True)

print(template.render())
这是我得到的结果:

This is some text that should have a single blank line below it.

line 0
line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9


This is some text that should have a single blank line above it.

但是,我正在尝试对其进行配置,以便在最后一行上方不会有两个空行,只有一个。

行{{I}
打印文本,后跟一个换行,然后有一个空行,使其成为两行。只需删除一个空行:

template = Template("""This is some text that should have a single blank line below it.

{% for i in range(10) -%}
line {{ i }}
{% endfor %}
This is some text that should have a single blank line above it."""

啊,我算出来了。我不正确地使用了环境。从文档中:

如果此类[Environment]的实例未共享且没有共享,则可以对其进行修改 模板已加载到目前为止。修改后的环境 加载的第一个模板将导致意外的效果和未定义的行为

下面是正确的代码

from jinja2 import Environment

template_string = """This is some text that should have a single blank line below it.

{% for i in range(10) -%}
line {{ i }}
{% endfor %}

This is some text that should have a single blank line above it."""

env = Environment(trim_blocks=True)

template = env.from_string(template_string)

print(template.render())
结果是:

This is some text that should have a single blank line below it.

line 0
line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9

This is some text that should have a single blank line above it.

对不起,这不是我真正想要的,因为我想修剪这些块,但那不起作用。不过还是要谢谢你的帮助!:)