在jinja2和flask中去除空白...为什么我仍然需要减号?

26 投票
3 回答
23879 浏览
提问于 2025-04-18 03:31

在我的 init.py 文件里,我有:

app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True

我希望在我的 jinja2 模板中,空白部分会被去掉,这样:

<div>
{% if x == 3 %}
<small>{{ x }}</small>
{% endif %}
</div>

就会显示成:

<div>
<small>3</small>
</div>

结果却出现了多余的空白:

<div>

<small>3</small>

</div>

为什么 trim_blocks 和 lstrip_blocks 没有去掉这些空白呢?

3 个回答

-1

如果你的代码在 macro.html 文件里,你必须手动添加 "-",不能使用下面的代码。

app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
1

你需要在{% if %}和{% endif %}语句前加一个减号,这样才能去掉空行:

<div>
{%- if x == 3 %}
<small>{{ x }}</small>
{%- endif %}
</div>
15

看起来你的环境设置在 jinja2 加载模板之前没有设置好。

class jinja2.Environment([options])

... 如果这个类的实例没有被共享,并且到目前为止没有加载任何模板,那么可以对它进行修改。如果在加载第一个模板后再修改环境设置,会导致一些意想不到的效果和不确定的行为。

http://jinja.pocoo.org/docs/dev/api/#jinja2.Environment

检查一下你的代码的顺序和结构,看看环境设置和模板是如何加载的。

顺便提一下,jinja2 的 空白控制 在没有环境和加载复杂性的情况下是可以正常工作的:

import jinja2

template_string = '''<div>
{% if x == 3 %}
<small>{{ x }}</small>
{% endif %}
</div>
'''
# create templates
template1 = jinja2.Template(template_string)
template2 = jinja2.Template(template_string, trim_blocks=True)

# render with and without settings
print template1.render(x=3)
print '\n<!-- {} -->\n'.format('-' * 32)
print template2.render(x=3)

<div>

<small>3</small>

</div>

<!-- -------------------------------- -->

<div>
<small>3</small>
</div>

我没有使用过 jinja2,但在浏览文档后,加载顺序似乎有问题。

撰写回答