从Jinja呈现的模板中删除不必要的空白 [英] Remove unnecessary whitespace from Jinja rendered template
问题描述
我正在使用 curl
来观看我的网络应用的输出。当Flask和Jinja渲染模板时,输出中会有很多不必要的空白。它似乎是通过从Flask-WTF和Flask-Bootstrap渲染各种组件来添加的。我可以用 sed
来解决这个问题,但是有没有办法从Jinja中控制这个?
最广泛的解决方案是设置 trim_blocks
和 lstrip_blocks
上的env。
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
如果要在文件末尾保留换行符,请设置 strip_trailing_newlines = False
。
您可以使用控制字符来修改块周围空白的工作方式。 -
总是删除空格, +
始终保留,覆盖该块的env设置。字符可以在块的开始或结尾(或两个)去控制空白方向。
<在
{%if ... +%}之前保留
{% - if ...%%}之前保留并剥离之后保留
记住`{%endif%}`被分开处理
请注意,控制字符只适用于模板你写。如果您包含模板或使用来自第三方的宏,那么他们写的模板将适用于该部分。
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 has multiple ways to control whitespace. It does not have a way to prettify output, you have to manually make sure everything looks "nice".
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
If you want to keep a newline at the end of the file, set strip_trailing_newlines = False
.
You can use control characters to modify how the whitespace around a block works. -
always removes whitespace, +
always preserves it, overriding the env settings for that block. The character can go at the beginning or end (or both) of a block to control the whitespace in that direction.
{%- if ... %} strips before
{% if ... +%} preserves after
{%+ if ... -%} preserves before and strips after
remember that `{% endif %}` is treated separately
Note that 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屋!