从数据库渲染文本时,Django 不显示换行符 [英] Django doesn't display newline character when rendering text from database

查看:24
本文介绍了从数据库渲染文本时,Django 不显示换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Django 进行开发,从数据库中检索一些包含换行符的文本.但是,当我使用模板标记将其呈现到模板时,它不会显示换行符.

有什么问题?

解决方案

您必须记住您的模板正在生成 HTML.在 HTML 中,换行符只是另一个空格,并不意味着将以下文本放到新行中.有多种方法可以在 HTML 中强制换行.

您可以使用 <pre> 标记包裹您的文本,以便 HTML 理解它是预先格式化的:

{{value}}

您可以使用 Django 过滤器将纯文本换行符转换为 HTML.linebreaks 将单个换行符转换为
标记,将双换行符转换为

标记.linebreaksbr 只是将换行符转换为
标签:

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

您可以尝试这些,看看您更喜欢哪一个.

否则,您可以在视图中使用字符串操作,以更适合您的方式将纯文本转换为 HTML.如果您想变得更高级,您可以编写自己的过滤器,以您喜欢的方式进行转换,并在整个模板中使用它.

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?

解决方案

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.

这篇关于从数据库渲染文本时,Django 不显示换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆