Home > OS >  How to replace line breaks (\n) with <br> for textual data to html content
How to replace line breaks (\n) with <br> for textual data to html content

Time:03-09

I am loading data from a database. The textual data has line breaks \n as uploaded by the user, I would like to print this data on a html page. However line breaks do not occur. I have tried replacing \n with <br>, but that prints with <br> as part of the string instead of actually breaking the line.

How I replace

value['description'].replace('\n', '<br>')

How it appears:

screenshot showing literal <br>s in text

CodePudding user response:

I have realized mine is a framework specific issue as guided by @Demian Wolf's comment, my html markup was getting escaped. Since I am using django framework, adding a safe call in was the solution.

{{ value.description | safe }}

CodePudding user response:

You can use the linebreaksbr templatetag

{{ value|linebreaksbr }}

or in your view

from django.template.defaultfilters import linebreaksbr
linebreaksbr(value['description'])
  • Related