Django doesn't display newline character when rendering text from database

前端 未结 2 1006
闹比i
闹比i 2020-12-02 09:23

I am using Django for development, retrieving some text containing a newline character from the database. However, when I render it to a template using a template tag it doe

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 10:01

    You have to remember that your templates are producing HTML. In HTML, a newline character is just another white space, it doesn't mean to put the following text onto a new line. There are a number of ways to force new lines in HTML.

    You can wrap your text with a

     tag so that HTML will understand that it is preformatted:

    {{value}}

    You can use Django filters to convert your plain text newlines into HTML. linebreaks turns single newlines into
    tags, and double newlines into

    tags. linebreaksbr just turns newlines into
    tags:

    {{value|linebreaks}}
    {{value|linebreaksbr}}
    

    You can experiment with these to see which you like better.

    Failing that, you can use string manipulation in your view to convert your plain text into HTML in a way that suits you better. And if you want to get really advanced, you can write your own filter that converts the way you like, and use it throughout your templates.

提交回复
热议问题