How to replace space into   in Django template?
Solution 1
For replacing a space with   , you may use one of following Template Tags based solution:
1) nbsp filter Replaces usual spaces in string by non breaking spaces
2) Regular Expression Replace Template Filter This will perform a regular expression search/replace on a string in your template.
3) Stackoverflow post, @Paolo Bergantino's answer Suggests to make a custom template tag
Solution 2
CSS
.nbsp {
white-space: nowrap;
}
Template
<div class="nbsp">Any text you want</div>
This should also help without processing text on server side.
Comments
-
Alfred Huang almost 2 years
I have a model with multiline text fields, which was input from a
textarea
.Now I want to render the field, but don't want to use
<pre>
tag.I just want to replace the new line with
<br/>
, and I found thelinebreakbr
filter.But I also want to replace space with
. Seemed not included in the documentation.Can anyone help?
-
alecxe over 9 yearsWhy don't u want to use
pre
? -
alecxe over 9 yearspossible duplicate of django templates stripping spaces?
-
Alfred Huang over 9 years@alecxe because it have some global style on it.
-
-
Flash almost 7 yearsNote that the nbsp filter in your first link lacks escaping of the value itself. It should say
mark_safe(" ".join(conditional_escape(value).split(' ')))
. -
Greg Kaleka over 5 years@Flash's comment is a good one. You'll need to add
from django.utils.html import conditional_escape
-
Greg Kaleka over 4 yearsNote this does not have the same effect as actual
characters, most notably for trailing spaces, which don't add to the width of a text element, while trailing
characters do.