从 Jinja 渲染模板中删除不必要的空白 [英] Remove unnecessary whitespace from Jinja rendered template
问题描述
我正在使用 curl
来观察我的网络应用程序的输出.当 Flask 和 Jinja 渲染模板时,输出中有很多不必要的空白.它似乎是通过从 Flask-WTF 和 Flask-Bootstrap 渲染各种组件来添加的.我可以使用 sed
剥离它,但是有没有办法从 Jinja 控制它?
I'm using curl
to watch the output of my web app. When Flask and Jinja render templates, there's a lot of unnecessary white space in the output. It seems to be added by rendering various components from Flask-WTF and Flask-Bootstrap. I could strip this using sed
, but is there a way to control this from Jinja?
推荐答案
Jinja 有多种方式控制空白.它没有美化输出的方法,您必须手动确保一切看起来不错".
Jinja has multiple ways to control whitespace. It does not have a way to prettify output, you have to manually make sure everything looks "nice".
最广泛的解决方案是在 env 上设置 trim_blocks
和 lstrip_blocks
.
The broadest solution is to set trim_blocks
and lstrip_blocks
on the env.
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
如果要在文件末尾保留换行符,请设置strip_trailing_newlines = False
.
If you want to keep a newline at the end of the file, set strip_trailing_newlines = False
.
您可以使用控制字符来修改标签周围空白的工作方式.-
总是删除空格, +
总是保留它,覆盖该标签的 env 设置.-
字符可以放在标签的开头或结尾(或两者)以控制该方向的空格,+
字符仅在标签的开头有意义标签.
You can use control characters to modify how the whitespace around a tag works. -
always removes whitespace, +
always preserves it, overriding the env settings for that tag. The -
character can go at the beginning or end (or both) of a tag to control the whitespace in that direction, the +
character only makes sense at the beginning of a tag.
{%- if ... %}
去掉之前{%- if ... -%}
前后去除{%+ if ... %}
保留之前{%+ if ... -%}
保留之前并删除之后- 记住
{% endif %}
是分开处理的
{%- if ... %}
strips before{%- if ... -%}
strips before and after{%+ if ... %}
preserves before{%+ if ... -%}
preserves before and strips after- remember that
{% endif %}
is treated separately
控制字符仅适用于您编写的模板.如果您包含模板或使用来自第 3 方的宏,那么他们编写的模板将适用于该部分.
The control characters only apply to templates you write. If you include a template or use a macro from a 3rd party, however they wrote the template will apply to that part.
这篇关于从 Jinja 渲染模板中删除不必要的空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!