How to replace space into &nbsp in Django template?

Alfred Huang picture Alfred Huang · Sep 18, 2014 · Viewed 9.4k times · Source

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?

Answer

Ali Raza Bhayani picture Ali Raza Bhayani · Sep 18, 2014

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