How to replace space into &nbsp in Django template?

11,630

Solution 1

For replacing a space with &nbsp , 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.

Share:
11,630
Alfred Huang
Author by

Alfred Huang

一切有为法, 如梦幻泡影。 如露亦如电, 应作如是观。

Updated on July 24, 2022

Comments

  • Alfred Huang
    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 the linebreakbr filter.

    But I also want to replace space with &nbsp;. Seemed not included in the documentation.

    Can anyone help?

    • alecxe
      alecxe over 9 years
      Why don't u want to use pre?
    • alecxe
      alecxe over 9 years
      possible duplicate of django templates stripping spaces?
    • Alfred Huang
      Alfred Huang over 9 years
      @alecxe because it have some global style on it.
  • Flash
    Flash almost 7 years
    Note that the nbsp filter in your first link lacks escaping of the value itself. It should say mark_safe("&nbsp;".join(conditional_escape(value).split(' '))).
  • Greg Kaleka
    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
    Greg Kaleka over 4 years
    Note this does not have the same effect as actual &nbsp; characters, most notably for trailing spaces, which don't add to the width of a text element, while trailing &nbsp; characters do.