Any way to add a new line from a string with the '\n' character in flask?
So it turns out that flask autoescapes html tags. So adding the <br>
tag just renders them on screen instead of actually creating line breaks.
There are two workarounds to this:
Break up the text into an array
text = text.split('\n')
And then within the template, use a for loop:
{% for para in text %} <p>{{para}}</p> {% endfor %}
Disable the autoescaping
First we replace the
\n
with<br>
using replace:text = text.replace('\n', '<br>')
Then we disable the autoescaping by surrounding the block where we require this with
{% autoescape false %} {{text}} {% endautoescape %}
However, we are discouraged from doing this:
Whenever you do this, please be very cautious about the variables you are using in this block.
I think the first version avoids the vulnerabilities present in the second version, while still being quite easy to understand.
Newlines only have an effect on HTML rendering in specific cases. You would need to use an HTML tag representing a newline, such as <br/>
.
def root():
str='yay<br/>super'
return str