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

前端 未结 5 600
一整个雨季
一整个雨季 2020-12-24 07:58

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

相关标签:
5条回答
  • 2020-12-24 08:03

    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

    0 讨论(0)
  • 2020-12-24 08:09

    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 }}
    
    0 讨论(0)
  • 2020-12-24 08:13
    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

    0 讨论(0)
  • 2020-12-24 08:18

    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
    
    0 讨论(0)
  • 2020-12-24 08:22

    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.

    0 讨论(0)
提交回复
热议问题