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.
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 }}
精彩评论