Home > Net >  how to avoid extra spacing in template while using if endif condition in template django
how to avoid extra spacing in template while using if endif condition in template django

Time:10-28

i am retrieving information from the database and using {%if%} and {%endif%} condition so if that field is blank it does not cause any problem but when that field does not have any value it creates a new blank line in place of that looks bad in styling I saw an answer use this {%if -%} {%- endif %}it doesn't work and throws the error all I want if field is blank do not create any new blank line and render second line below that without creating any whitespace any suggestion will be helpfull

CodePudding user response:

You could format like this:

My first line{% if second_line %}<br>
{{second_line}}{% endif %}<br>
My third line

The idea being if second_line doesn't exist it won't render that <br>

CodePudding user response:

You can use the built in templatetag

{% spaceless %}
    Space less content here
{% endspaceless %}

As per the documentation that can be found here:

https://docs.djangoproject.com/en/4.1/ref/templates/builtins/#spaceless

Thespaceless tag:

Removes whitespace between HTML tags. This includes tab characters and newlines.

{% spaceless %}
    <p>
        <a href="foo/">Foo</a>
    </p>
{% endspaceless %}

Would result in:

<p><a href="foo/">Foo</a></p>
  • Related