我创建了一个Web应用程序,我正在使用django生成的管理员插入一些数据。特别是,我有以下字段:
description = models.TextField(max_length=10000, null=True, blank=True)
在管理员中,它显示为文本区域,我可以在其中插入新的空行。但是当我插入类似的东西时
一些文本后跟一个新的 emtpy 行。
其他一些文本。
我在调用 REST API 的 HTML 页面中获得的结果如下所示:
Some text followed by a new emtpy line. Some other text.
因此,一些空格将代替新行。如果我删除空行并只插入换行符,则空格的数量会减少。
访问该字段的 REST API 将返回以下内容:
一些文本后跟一个新的 emtpy 行。\r\r一些其他文本。
如果描述已正确存储到数据库中,如何保留空行?
这个问题可以通过为文本容器添加一个 css 指令来解决:
white-space: pre-line;
我用换行符解决了这个问题 它会在 html 中将换行符转换为 br 标签。例如:
<p>{{ description | linebreaks}}</p>
使用自动转义和安全过滤器,它不仅适用于/n/r,也适用于其他富文本标签。
我使用了这样的东西:
{% autoescape on %}
<div>{{ description|safe }}</div>
{% endautoescape %}
您可以将换行符转换为换行符。
description = description.replace('rn', '<br />')
在模板中,使用 safe
筛选器将其输出。
{{ description | safe }}
safe
过滤器禁用 html 缓存。 https://docs.djangoproject.com/en/dev/ref/templates/builtins/#safe