Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

python - Remove unnecessary whitespace from Jinja rendered template

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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 ... %} strips before
  • {%- if ... -%} strips before and after
  • {%+ if ... %} preserves before
  • {%+ if ... -%} preserves before and strips after
  • remember that {% endif %} is treated separately

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...