开发者

Django template link with if else statement

开发者 https://www.devze.com 2023-03-29 17:59 出处:网络
Lets say I have code in template like this: <a href=\"#\"> {% if request.user.first_name or request.user.last_name %}

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.


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


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/


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


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?


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

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

精彩评论

暂无评论...
验证码 换一张
取 消