mc_kaiser
mc_kaiser

Reputation: 757

How to remove whitespace around a character in a Django Template?

I have a template that looks like this:

({% if condition_a %}
 <a href="{{ link_a }}" role="button">Add</a>
{% endif %}
{% if condtion_a and condition_b %} | {% endif %}
{% if condition_b %}
 <a href="{{ link_b }}">Edit</a>
{% endif %})

I was hoping it would render with the parentheses next to the words. For example, in the case of condition_a:

(Add)

But due to the way html handles line breaks, the page is rendered like this:

( Add )

The same is true for the other conditions (ie. condition_a and conditon_b):

Expected:

(Add | Edit)

Result:

( Add | Edit )

I tried adding the Django spaceless tag, but that didn't work as it only strips whitespace around html tags. I could jam a few more if statements in to my code, but would prefer not to.

I also tried adding white-space: nowrap; to the css but that failed as well.

Is there any way I can trim the whitespace around words?

Upvotes: 0

Views: 1384

Answers (1)

Action Jackson
Action Jackson

Reputation: 1206

Do this:

{% if condtion_a and condition_b %}
    <a href="{{ link_a }}">(Add</a> | <a href="{{ link_b }}">Edit)</a>
{% elif condition_a %}
    <a href="{{ link_a }}">(Add)</a>
{% elif condition_b %}
    <a href="{{ link_b }}">(Edit)</a>
{% endif %}

Don't spread out your code between that many lines wrapped in parentheses. Just add them directly inside the <a> tag instead. And to clean up your code, I also suggest putting the condition_a and condition_b up top first so you don't have to start and stop so many if statements (you have 3 endif's, that's not a good habit to follow when it can be done more cleanly).

You could also put a and b in an else statement at the bottom, but I don't know the code in your view so that might not be a good idea.

Upvotes: 3

Related Questions