从Jinja呈现的模板中删除不必要的空白 [英] Remove unnecessary whitespace from Jinja rendered template

查看:378
本文介绍了从Jinja呈现的模板中删除不必要的空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 curl 来观看我的网络应用的输出。当Flask和Jinja渲染模板时,输出中会有很多不必要的空白。它似乎是通过从Flask-WTF和Flask-Bootstrap渲染各种组件来添加的。我可以用 sed 来解决这个问题,但是有没有办法从Jinja中控制这个?

解决方案< 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屋!

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