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

Question:

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='yaynsuper'
    return str
test.run(debug=True)
Asked By: ollien

||

Answers:

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
Answered By: David Robinson

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.

Answered By: Samarth Hattangady
  1. works for me and preserves security

I would suggest <br> rather than <p>

{% for para in text %}
    {{para}}<br>
{% endfor %}

then result is less bulky

Answered By: Pascal Louis-Marie

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 }}
Answered By: Zep

I come late to the party, but here’s my solution.
HTML has a <pre> tag which can prove useful in this situation.

<pre>{{ your_text }}</pre>

This tag tells the browser not to automatically adjust spacing and line breaks.
To learn more about this tag check this guide out.

Answered By: Nicholas Obert

Easiest way to do this

  1. Create your template filter
@app.template_filter(name='linebreaksbr')
def linebreaksbr_filter(text):
    return text.replace('n', '<br>')
  1. Add this to your template
{{ someText|linebreaksbr }}

This will replace every "n" character in your text with <br>.

Answered By: Lakshyaraj Dash
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.