怎样用 Python(Django)字符串和HTML读取和打印带有换行符的文本?

2024-06-09 10:21:58 发布

您现在位置:Python中文网/ 问答频道 /正文

如果有人输入短语,例如:

I see you driving

round town with the girl I love,

and I’m like: haiku.

(每一行之间没有空行,但是文本被写在三个单独的行上)到一个网页上的文本框中,然后按一个按钮,然后通过Django存储在数据库中,然后该字符串被读回并打印在页面上,我如何才能让它在HTML页面上打印,而新行仍然在文本中?在

所以不是打印回: I see you driving round town with the girl I love, and I’m like: haiku.

它将打印为:

I see you driving

round town with the girl I love,

and I’m like: haiku.

我知道如果我使用:(textarea)soAndSo.body(/textarea),这将保留用户最初键入文件时文件中的新行。我怎样才能得到同样的效果,但不必使用textarea盒?在


Tags: andthe文本youwith页面likehaiku
3条回答

<pre>中包装输出将保留格式,<pre>soAndSo.body</pre>

更高级的解决方案包括将换行转换为HTML段落或换行符。Django为此提供了内置过滤器:linebreaks和{a2}都可以做到这一点。在

如果要使用这些,请按如下方式过滤输出:{{ soAndSo.body|linebreaks }}

在模板中使用linebreaksbr(或linebreaks)过滤器。在

For example:

{{ value|linebreaksbr }}

If value is Joel\nis a slug, the output will be Joel<br />is a slug.

虽然将换行符\r\n替换为<br/>绝对是一个选择,但您可能需要考虑css ^{} property

#haiku {white-space:pre;}

Fiddled,值得注意的是the property is surprisingly well-supported,即使是在IE6+

相关问题 更多 >