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领域中,执行
.replace('\n', '<br>')
.但这使您容易受到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('\n', '<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屋!
查看全文