[英]Trimming blocks using whitespace control from jinja2 template
I'm trying to print a single blank line surrounding the results of a jinja2 for loop, but I just can't get it to work. 我正在尝试在jinja2 for循环的结果周围打印一行空白行,但是我无法使其正常工作。 Can someone tell me what I am doing wrong? 有人可以告诉我我在做什么错吗?
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 the result I get: 这是我得到的结果:
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.
However, I'm trying to configure it so that I don't get two blank lines above the final line, only one. 但是,我正在尝试对其进行配置,以使我不会在最后一行的上方得到两个空白行,而只能得到一个空白行。
Ah, I worked it out. 啊,我解决了。 I was using the environment incorrectly. 我使用环境不正确。 From the docs: 从文档:
Instances of this class [Environment] may be modified if they are not shared and if no template was loaded so far. 如果此类[Environment]的实例不共享并且到目前为止尚未加载任何模板,则可以对其进行修改。 Modifications on environments after the first template was loaded will lead to surprising effects and undefined behavior. 加载第一个模板后对环境的修改将导致令人惊讶的效果和不确定的行为。
The correct code is below 正确的代码如下
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())
and the result: 结果:
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 }}
prints text followed by a newline, then you have an empty lines which makes it two. line {{ i }}
打印文本,后跟换行符,然后空line {{ i }}
其变为两个。 Simply remove an empty line: 只需删除一个空行:
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.