How to replace '\n' in string with '<br>' in Flask app?

Viewed 1594

I've been trying to modify a string before passing it to my HTML page in Flask (replacing occurrences of '\n' with '<br>'), but the typical methods I use aren't working for some reason.

finalstring = textstring.replace('\n', '<br>')
return render_template('my-form-result.html', emailresponse = finalstring)

This should work, but for some reason, nothing is replaced. How can I get this to work? Thanks!

3 Answers

A better way to replace \n in HTML is using CSS styles.

Your replace() is alright. Debug your code and make sure there is \n before replace().

To be able to view linebreaks in HTML you should use safe filter in the template. But beware that you become open to XSS attacks. To get round this problem you should escape the string before replacing the \n character. This is the code:

from flask import escape

...
...
    safe_html = str(escape(text)).replace('\n', '<br/>')
    return render_template('[HTML file].html', safe_html=safe_html)

---------
#in the template:
   <span> {{ safe_html | safe }} </span>

If you don't use the str() call before replace, then the <br/> will be scaped too. Because the return value from escape() is not string.

Disclaimer: I never worked with Flask, I just looked it up and hope it does what you want to do.

So somewhere in your template my-form-result.html you should find a line containing:

{{ emailresponse }}

You can replace this with:

{% for line in emailresponse.split('\n') %}
{{ line }}
<br />
{% endfor %}

To add an br after every newline

Your replace() code is correct. Make sure you escape the HTML in the template:

{{ emailresponse|safe }}

To diagnose, try this:

finalstring = textstring.replace('\n', '<br>')
print(finalstring)
return render_template('my-form-result.html', emailresponse = finalstring)

Also, show us the source code from the web page, to see what is actually rendering in the template

Related