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

喜夏-厌秋 提交于 2019-12-17 15:24:45

问题


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 doesn't show the newline character.

What is the problem?


回答1:


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 <pre> tag so that HTML will understand that it is preformatted:

<pre>{{value}}</pre>

You can use Django filters to convert your plain text newlines into HTML. linebreaks turns single newlines into <br> tags, and double newlines into <p> tags. linebreaksbr just turns newlines into <br> 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.




回答2:


Not sure if I totally understand your question, but try using the linebreaks filter.

{{ value|linebreaks }}


来源:https://stackoverflow.com/questions/1356048/django-doesnt-display-newline-character-when-rendering-text-from-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!