Jinja 在保留换行符的 HTML 中渲染文本 [英] Jinja render text in HTML preserving line breaks
本文介绍了Jinja 在保留换行符的 HTML 中渲染文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的简单表格:
I have a simple form like this:
class RecordForm(Form):
notes = TextAreaField('Notes')
我把数据分成三段这样记录:
I record the data in three paragraphs like this:
para1
para2
para3
在模板中,我想以只读方式查看该记录的内容.(不可编辑的表单)
In the template I would like to see the content of that record in read-only. (Not editable form)
记录本例中包含数据的模型:
record is this case the model containing the data:
<td>{{ record.notes }}</td>
-->
<td>para1 para2 para3</td>
我该怎么做才能显示多行?
What can I do to make it to show the multi-lines?
推荐答案
所有空格,包括换行符,在 HTML 中都变成了一个空格.
All whitespace, including newlines, is turned into a single space in HTML.
您的选择,从最好到最坏:
Your options, from best to worst:
- 将
white-space: pre-wrap;
放在包含元素上.这告诉 HTML 完全按照源代码中出现的方式显示所有空格,包括换行符.(您也可以使用<pre>
标签,但这也会禁用自动换行,这可能是您不想要的.) - 将纯文本视为 Markdown 并在其中使用 Markdown 处理器——Markdown 所做的一件事就是将段落包裹在
<p>
中. - 在 Python-land 中,执行
.replace(' ', '
.但这会使您容易受到 XSS 的攻击,因为字符串中可能存在其他类似 HTML 的垃圾,修复它有点麻烦.
')
- Put
white-space: pre-wrap;
on the containing element. This tells HTML to show all whitespace exactly as it appears in the source, including newlines. (You could also use a<pre>
tag, but that will also disable word-wrapping, which you probably don't want.) - Treat the plain text as Markdown and throw a Markdown processor at it—one of the things Markdown does is wrap paragraphs in
<p>
. - In Python-land, do
.replace(' ', '<br>')
. But this leaves you vulnerable to XSS because there might be other HTML-like junk in the string, and fixing that is a bit of a pain.
这篇关于Jinja 在保留换行符的 HTML 中渲染文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文