djlint / djLint

✨ HTML Template Linter and Formatter. Django - Jinja - Nunjucks - Handlebars - GoLang
https://djLint.com
GNU General Public License v3.0
664 stars 81 forks source link

[Formatter] jinja whitespace control and formatter inline whitespace removal #841

Open anentropic opened 2 months ago

anentropic commented 2 months ago

System Info

Issue

I have some jinja that is formatted like this after formatting:

                <tr {% if stat.css_classes %}
                    class="{{ stat.css_classes }}"
                    {% endif %}>

I am trying to use jinja whitespace control to end up with rendered html like:

                <tr class="text-warning">

I've enabled trim_blocks and lstrip_blocks

I can do this:

                <tr {% if stat.css_classes -%}
                    class="{{ stat.css_classes }}"
                    {%- endif %}>

and get:

                <tr class="text-warning">

But in the case where the conditional is false I still have an extra whitespace:

                <tr >

I could do this:

                <tr {%- if stat.css_classes %} class="{{ stat.css_classes }}"{% endif %}>

and all the cases would look right when rendered

But the formatter wants to get rid of the inner whitespace here %} class

...it's this behaviour I'd like to have control over - maybe an option to preserve such whitespace?

Other option that works right now is:

                <tr {%- if stat.css_classes -%}
                    {{ ' ' }}class="{{ stat.css_classes }}"
                    {%- endif %}>

{{ ' ' }} makes a whitespace that resists being collapsed by either jinja or the formatter, which allows to contract the regular whitespace aggressively on jinja side

construct is a bit ugly but maybe this is best option after all

however the formatter now wants to put that on one line:

                <tr {%- if stat.css_classes -%}{{ ' ' }}class="{{ stat.css_classes }}"{%- endif %}>

that's ok for me, but if I can't have multi-line formatting I'd rather be able to have a normal whitespace

How To Reproduce

see above