在Jinja2&中剥离空格烧瓶...为什么我还需要减号? [英] Stripping whitespace in jinja2 & flask...why do I still need the minus sign?

查看:58
本文介绍了在Jinja2&中剥离空格烧瓶...为什么我还需要减号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my init.py file I have:

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

我希望在我的jinja2模板中会修剪空格,以便:

I expect in my jinja2 template that whitespace will be trimmed, so that:

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

将呈现为:

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

相反,我得到了额外的空格:

Instead, I get extra whitespace:

<div>

<small>3</small>

</div>

为什么没有trim_blocks和lstrip_blocks修剪空白?

Why doesn't trim_blocks and lstrip_blocks trim the whitespace?

推荐答案

在 jinja2加载模板之前,似乎未设置您的环境设置.

It seems like your environment settings are not set before jinja2 loads your template.

jinja2.Environment类([选项])

...如果此类实例没有共享,并且如果到目前为止尚未加载模板,则可以对其进行修改.在第一个模板加载后对环境的修改将导致令人惊讶的效果,并且不确定行为.

... 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.环境

检查代码的顺序/结构,以了解如何加载环境设置和模板.

Check the order/structure of your code to see how the environment settings vs templates are loaded.

顺便说一句,jinja2的空白控件确实可以正常工作而不需要复杂的环境和负载:

As an aside, jinja2's whitespace control does work as expected without the complexity of environments and loading:

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,但是在扫描了文档之后,加载顺序似乎令人怀疑.

I've not used jinja2, but after scanning the docs, loading order seems to be suspect.

这篇关于在Jinja2&amp;中剥离空格烧瓶...为什么我还需要减号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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