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

前端 未结 5 674
一整个雨季
一整个雨季 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:22

    So it turns out that flask autoescapes html tags. So adding the
    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 %}
          

      {{para}}

      {% endfor %}
    2. Disable the autoescaping

      First we replace the \n with
      using replace:

      text = text.replace('\n', '
      ')

      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.

提交回复
热议问题