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 there but it didn't work, any ideas?
from flask import Flask from flask import render_template test=Flask(__name__) @test.route('/') def root(): str='yay\nsuper' return str test.run(debug=True)
Inserting a newline code \n , \r\n into a string will result in a line break at that location. On Unix, including Mac, \n (LF) is often used, and on Windows, \r\n (CR + LF) is often used as a newline code.
Newline character in Python: In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line.
Markup is a direct subclass of unicode and provides all the methods of unicode just that it escapes arguments passed and always returns Markup . The escape function returns markup objects so that double escaping can't happen.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With