在我的init .py文件中,我有:
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
Run Code Online (Sandbox Code Playgroud)
我期望在我的jinja2模板中修剪空白,以便:
<div>
{% if x == 3 %}
<small>{{ x }}</small>
{% endif %}
</div>
Run Code Online (Sandbox Code Playgroud)
将呈现为:
<div>
<small>3</small>
</div>
Run Code Online (Sandbox Code Playgroud)
相反,我得到额外的空格:
<div>
<small>3</small>
</div>
Run Code Online (Sandbox Code Playgroud)
为什么trim_blocks和lstrip_blocks不修剪空白?
在 jinja2加载模板之前,似乎没有设置环境设置.
class jinja2.Environment([options])
...如果未共享此类的实例,并且到目前为止尚未加载模板,则可以修改此类的实例.加载第一个模板后对环境的修改将导致令人惊讶的效果和未定义的行为.
检查代码的顺序/结构,以查看环境设置与模板的加载方式.
顺便说一句,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)
Run Code Online (Sandbox Code Playgroud)
<div>
<small>3</small>
</div>
<!-- -------------------------------- -->
<div>
<small>3</small>
</div>
Run Code Online (Sandbox Code Playgroud)
我没有使用jinja2,但在扫描文档后,加载顺序似乎是可疑的.