Html 从数据库渲染文本时,Django 不显示换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1356048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django doesn't display newline character when rendering text from database
提问by Nazmul Hasan
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.
我正在使用 Django 进行开发,从数据库中检索一些包含换行符的文本。但是,当我使用模板标记将其呈现到模板时,它不会显示换行符。
What is the problem?
问题是什么?
回答by Ned Batchelder
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.
您必须记住您的模板正在生成 HTML。在 HTML 中,换行符只是另一个空格,并不意味着将以下文本放到新行中。有多种方法可以在 HTML 中强制换行。
You can wrap your text with a <pre>
tag so that HTML will understand that it is preformatted:
你可以用一个<pre>
标签包裹你的文本,这样 HTML 就会明白它是预先格式化的:
<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:
您可以使用 Django 过滤器将纯文本换行符转换为 HTML。linebreaks
将单个换行符转换为<br>
标签,将双换行符转换为<p>
标签。linebreaksbr
只是将换行符转换为<br>
标签:
{{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.
否则,您可以在视图中使用字符串操作,以更适合您的方式将纯文本转换为 HTML。如果您想变得更高级,您可以编写自己的过滤器,以您喜欢的方式进行转换,并在整个模板中使用它。
回答by David
Not sure if I totally understand your question, but try using the linebreaks filter.
不确定我是否完全理解您的问题,但请尝试使用换行符过滤器。
{{ value|linebreaks }}