[英]Trimming blocks using whitespace control from jinja2 template
我正在尝试在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.
但是,我正在尝试对其进行配置,以使我不会在最后一行的上方得到两个空白行,而只能得到一个空白行。
啊,我解决了。 我使用环境不正确。 从文档:
如果此类[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.
line {{ i }}
打印文本,后跟换行符,然后空line {{ 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."""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.