Lets say I have code in template like this:

<a href="#">
    {% if request.user.first_name or request.user.last_name %}
        {{ request.user.first_name }} {{ request.user.last_name }}
    {% else %}
        {{ request.user }}
    {% endif %}
</a>

Problem with this code is that it adds trailing space to link, so link looks like link_ with underline at the end.

How do I remove such trailing spaces? {% spaceless %} tag doesn't quite help here because it only removes spaces between tags.

score:9

Accepted answer

I actually found simple solution for my problem.

<a href="#">{% spaceless %}
    {% if request.user.first_name or request.user.last_name %}
        {{ request.user.first_name }} {{ request.user.last_name }}
    {% else %}
        {{ request.user }}
    {% endif %}
{% endspaceless %}</a>

By placing spaceless tag inside it strips the string it gets. Placing outside

Similar question

score:0

Quick workaround: Use html comments to "escape" the unnecessary whitespace. Probably better solution: Create a template tag that holds this conditional.

score:0

Seconding the usage of a single template tag - it'd be good (and pretty easy) to remove this logic from the template.

Although, doesn't just using {{ request.user }} give exactly the same result as what you're doing here?

score:0

Instead of if-else block try to use shorter version:

{{ user.get_full_name|default:user.get_username }}

score:1

As a possible variant of decision: http://www.soyoucode.com/2011/minify-html-output-django

Or you could try to create your own tag if there are no such tags: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/