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

时间:2016-03-12 10:39:49

标签: 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 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.

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

2 个答案:

答案 0 :(得分:2)

啊,我把它解决了。我错误地使用了环境。来自文档:

  

如果不共享此类[Environment]的实例,则可以修改它们的实例   模板已加载到目前为止。对环境后的环境进行修改   加载第一个模板将导致令人惊讶的效果和未定义的行为。

正确的代码在

之下
def num_to_word(num):
    num_dict = {'0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine'}
    return ' '.join([num_dict[x] for x in str(num)])

结果:

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())

答案 1 :(得分:1)

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."""