在jinja2&flask中去掉空白…为什么我还需要减号?

2024-04-28 11:24:52 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的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>

为什么不修剪块和lstrip块修剪空白?


Tags: 文件pydivenv模板trueappjinja2
2条回答

在jinja2加载模板之前,似乎没有设置环境设置。

class jinja2.Environment([options])

... Instances of this class 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.

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

检查代码的顺序/结构,查看环境设置与模板的加载方式。

顺便说一下,jinja2的whitespace control确实可以按预期工作,而不需要复杂的环境和加载:

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,但扫描完文档后,加载顺序似乎有问题。

您必须用减号转义{%if%}和{%endif%}语句,以抑制空行:

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

相关问题 更多 >