Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to add a new line from a string with the '\n' character in flask?

Tags:

python

flask

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) 
like image 549
ollien Avatar asked Sep 03 '12 08:09

ollien


People also ask

How do you add a line break in string?

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.

How do you add a new line to a string in Python?

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.

What is markup in flask?

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.


1 Answers

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:

  1. 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 %} 
  2. 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.

like image 194
Samarth Hattangady Avatar answered Sep 27 '22 22:09

Samarth Hattangady