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?
Jinja2 allows us to manually control generation of whitespaces. You do it by using a minus sing - to strip whitespaces from blocks, comments or variable expressions. You need to add it to the start or end of given expression to remove whitespaces before or after the block, respectively.
To reuse a Jinja template you use the Jinja built-in {% extends %} tag. The {% extends %} tag uses the syntax {% extends <name> %} to reuse the layout of another template. This means that in order to reuse the layout in listing 4-5 defined in a file base.
July 20, 2021. Jinja2 is a popular text templating engine for Python that is also used heavily with Ansible. Many network engineers are familiar with it and with leveraging Jinja2 templates for device configurations.
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{% endif %}
is treated separatelyThe 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With