【问题标题】:Stripping whitespace in jinja2 & flask...why do I still need the minus sign?去除 jinja2 和烧瓶中的空格......为什么我还需要减号?
【发布时间】:2014-04-20 19:31:00
【问题描述】:

在我的 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 不修剪空白?

【问题讨论】:

  • 我无法重现它(Jinja 2.7.3)。在 Firefox 和 Chrome 中查看呈现的源代码显示模板呈现正确,没有额外的换行符。这里有几个可能的原因。这可能是 jinja2 问题,但如果您在一个平台上开发并在另一个平台上查看,它也可能是编辑器或 linux-windows 问题(例如superuser.com/questions/374028/…
  • 我赞同@tohster 的评论。您是否将赋值语句放在错误的位置?你能发布完整的源代码吗?

标签: python jinja2


【解决方案1】:

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

class jinja2.Environment([options])

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

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,但是在扫描文档后,加载顺序似乎很可疑。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    猜你喜欢
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    • 2019-12-31
    相关资源
    最近更新 更多