使用Jinja2模板中的空白控件修剪块 [英] Trimming blocks using whitespace control from jinja2 template

查看:94
本文介绍了使用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:

如果没有共享并且没有,则可以修改此类[Environment]的实例 模板已加载到此为止.修改后的环境 加载第一个模板会导致令人惊讶的效果和不确定的行为.

Instances of this class [Environment] may be modified if they are not shared and if no template was loaded so far. Modifications on environments after the first template was loaded will lead to surprising effects and undefined behavior.

正确的代码在下面

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模板中的空白控件修剪块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆