我正在创建一个笔记应用,用户可以通过在textarea中输入多行文字来添加笔记。当我在Firebase中保存笔记时,它将使用我想要显示的换行符(\ n)保存。
因此,我写了一个过滤器,用<br />
取代这些字符,效果很好
但是,现在我需要使用{{{note.content}}}
来渲染我的数据,并且用户可以注入将要执行的HTML,CSS和JS。
我应该使用类似DOMPurify的内容来验证内容,还是有办法安全地呈现换行符?
答案 0 :(得分:86)
正如@shelvacu所说, <pre>
html标签会保留空格。
但是使用它有一个严重的缺点:标签本身从项目中使用的CSS框架(例如Bootstrap)继承了大量不必要的样式。
要保留空格并避免继承任何不必要的样式,请使用:
<span style="white-space: pre;">Some whitespaced content</span>
会像<pre>
标签那样行事。
请注意,white-space: pre
仍为“文字”,如果您希望在必要时使用其他换行符:white-space: pre-wrap
。
答案 1 :(得分:28)
pre
元素中。 <pre>
元素预会在其中提供空白,例如:
This is followed by a newline,
not that you can tell
<br />
<br />
<pre>You can see the newline after me!
Woohoo!</pre>
将导致:
This is followed by a newline, not that you can tell
You can see the newline after me!
Woohoo!
这样,您就不需要对换行进行任何过滤。
答案 2 :(得分:22)
在实际描述我的问题后,我明白了使用预格式文本的预标签。此标记将尊重&#39; \ t \ n&#39;字符并正确地呈现文本! 虽然句子不会自动破坏并溢出宽度。 通过一些CSS,我能够获得与其他元素相同的行为。
HTML:
{{note.content}}
的CSS:
.note pre {
white-space: pre-wrap;
word-wrap: break-word;
font-family: inherit;
}
答案 3 :(得分:7)
希望这能为新访问者增加价值。
I am big line with lots and lots of text which would make me not fit.
Line two ✌
Line three
<span style="white-space: pre-line">Your Content</span>
<span style="white-space: pre">Your Content</span>
参考及更多详情:https://css-tricks.com/almanac/properties/w/whitespace
答案 4 :(得分:3)
答案 5 :(得分:3)
我不是 pre
的忠实粉丝(除了调试!)所以这里是另一种使用 v-for
处理这个问题的方法。这样可以更轻松地调整格式(例如,您可能想使用列表或其他不是 span
和 br
的内容)
<span
v-for="(line,lineNumber) of stringWithNewlines.split('\n')"
v-bind:key="lineNumber" >
{{ line }}<br/>
</span>
答案 6 :(得分:1)
我能够使用反引号(`)
<pre>{{textRenderedAsItIs}}<pre>
data():{
return{
textRenderedAsItIs:`Hello
World`
}
}
答案 7 :(得分:1)
将\ n转换为
if (this.content.my_val && this.content.my_val !== '') {
return this.content.my_val.replace(/\n/g, '<br />')
}