I was playing around with flask when I came across an odd problem with the \'\\n\' character. it dosen\'t seem to have an effect in my browser, I tried putting
in the
Disable auto escaping
your_arr = your_arr.replace('\n', '<br>')
{% for your_text in your_arr %}
{{ (your_text | safe) }}
{% endfor %}
Note: With | safe Jinja2 will print symbols as they are in your variable, that means that it won't translate "dangerous" symbols into html entities (that Jinja2 does by default to escape "dangerous" ones). Use this option if you trust variable's content... Read more
In case someone end up here like me, and doesn't want to use {% autoescape false %}, for safety reasons, nor braking up the text which might be inconvenient in some cases, I found a good alternative here:
from flask import Markup
value = Markup('First line.<br>Second line.<br>')
and then in the jinja template:
{{ value }}
I would suggest <br>
rather than <p>
{% for para in text %}
{{para}}<br>
{% endfor %}
then result is less bulky
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
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.