Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template link with if else statement

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.

like image 561
Marius Grigaitis Avatar asked Aug 22 '11 20:08

Marius Grigaitis


People also ask

What does {% %} mean in Django?

{% extends variable %} uses the value of variable . If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.

What {% include %} does?

{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.

What is Forloop counter in Django?

A for loop is used for iterating over a sequence, like looping over items in an array, a list, or a dictionary.


2 Answers

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

like image 132
Marius Grigaitis Avatar answered Nov 01 '22 15:11

Marius Grigaitis


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/

like image 36
sergzach Avatar answered Nov 01 '22 15:11

sergzach