Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

{% spaceless %} tag for Jinja templates?

Tags:

jinja2

Django has a useful {% spaceless %} tag that strips extra whitespace from HTML.

My templates are producing a lot of whitespace and it's too much of a pain to add the {%- and -%} everywhere to do whitespace control. Has anyone seen a filter like {% spaceless %} for Jinja, or maybe {% htmltidy %}, so that I could view clean HTML while developing?

like image 974
a paid nerd Avatar asked Mar 04 '11 07:03

a paid nerd


People also ask

What are Jinja tags?

Jinja is similar to the Django template engine but provides Python-like expressions while ensuring that the templates are evaluated in a sandbox. It is a text-based template language and thus can be used to generate any markup as well as source code. Jinja. Original author(s) Armin Ronacher.

How do you get rid of whitespace in 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.

How do you declare a variable in Jinja template?

{{ }} tells the template to print the value, this won't work in expressions like you're trying to do. Instead, use the {% set %} template tag and then assign the value the same way you would in normal python code. It was great explanation and simple one.


1 Answers

There is a jinja2 extension that achieves this effect, authored by the jinja2 developer

https://github.com/mitsuhiko/jinja2-htmlcompress

like image 50
Mr Hyde Avatar answered Sep 27 '22 23:09

Mr Hyde