简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM