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:

  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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)