本文介绍了使用Jinja2模板中的空白控件修剪块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在jinja2 for循环的结果周围打印一行空白行,但是我无法使其正常工作.有人可以告诉我我在做什么错吗?

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

正确的代码在下面

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.

这篇关于使用Jinja2模板中的空白控件修剪块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 11:30