Python 从 Jinja 渲染模板中删除不必要的空白
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35775207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove unnecessary whitespace from Jinja rendered template
提问by Hexatonic
I'm using curlto 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?
我正在使用curl来观看我的网络应用程序的输出。当 Flask 和 Jinja 渲染模板时,输出中有很多不必要的空白。它似乎是通过从 Flask-WTF 和 Flask-Bootstrap 渲染各种组件来添加的。我可以使用 剥离它sed,但是有没有办法从 Jinja 控制它?
回答by davidism
Jinja has multiple ways to control whitespace. It does nothave a way to prettify output, you have to manually make sure everything looks "nice".
Jinja 有多种方法来控制空白。它没有美化输出的方法,您必须手动确保一切看起来“不错”。
The broadest solution is to set trim_blocksand lstrip_blockson the env.
最广泛的解决方案是在 env 上设置trim_blocks和lstrip_blocks。
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.
如果要在文件末尾保留换行符,请设置strip_trailing_newlines = False.
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.
您可以使用控制字符来修改标签周围空白的工作方式。 -始终删除空格,+始终保留它,覆盖该标签的 env 设置。该-角色可以在标签的开头或结尾(或两者)去控制空格这个方向发展,该+字符才有意义,在标签的开始。
{%- if ... %}strips before{%- if ... -%}strips before and after{%+ if ... %}preserves before{%+ if ... -%}preserves before and strips after- remember that
{% endif %}is treated separately
{%- if ... %}前条{%- if ... -%}之前和之后的条带{%+ if ... %}之前保存{%+ if ... -%}保留之前和之后剥离- 记住
{% endif %}是分开处理的
The control characters only apply to templates youwrite. If you include a template or use a macro from a 3rd party, however they wrote the template will apply to that part.
控制字符仅适用于您编写的模板。如果您包含模板或使用来自 3rd 方的宏,那么他们编写的模板将适用于该部分。
回答by Anas
To collapse whitespace before and after a block:
要在块之前和之后折叠空白:
{%- if form.message -%} //trims before
{{ form.message }}
{%- endif -%} // trims after

