在 HTML 中呈现字符串并保留空格和换行符

问题描述 投票:0回答:8

我有一个带有详细信息页面的 MVC3 应用程序。作为其中的一部分,我有一个包含空格和换行符的描述(从数据库中检索)。渲染时,新行和空格将被 html 忽略。我想对这些空格和新行进行编码,这样它们就不会被忽略。

你是怎么做到的?

我尝试了 HTML.Encode 但它最终显示了编码(甚至不在空格和换行符上,而是在其他一些特殊字符上)

html css newline whitespace line-breaks
8个回答
813
投票

只需使用

white-space: pre-wrap;
来设计内容。

div {
    white-space: pre-wrap;
}
<div>
This is some text   with some extra spacing    and a
few newlines along with some trailing spaces        
     and five leading spaces thrown in
for                                              good
measure                                              
</div>


65
投票

您是否尝试过使用

<pre>
标签。

 <pre>
    
    Text with
    
    multipel line breaks embeded between pre tag
    
    will work    and 
       also tabs..will work
    
it will preserve the formatting..
    </pre>


48
投票

您可以使用 white-space: pre-line 来保留格式中的换行符。无需手动插入html元素。

.popover {
    white-space: pre-line;    
}

或添加到您的html元素

style="white-space: pre-line;"


7
投票

您可能希望将所有空格替换为

&nbsp;
(不间断空格),将所有新行
\n
替换为
<br>
(html 中的换行符)。这应该可以达到您正在寻找的结果。

body = body.replace(' ', '&nbsp;').replace('\n', '<br>');

那种性质的东西。


4
投票

我正在尝试 pete 所说的

white-space: pre-wrap;
技术,但是如果绳子是连续的并且很长,它就会从容器中跑出来,并且不会因为任何原因而翘曲,没有太多时间去调查..但是如果你也有同样的问题,我最终使用了
<pre>
标签和下面的CSS,一切都很好..

pre {
font-size: inherit;
color: inherit;
border: initial;
padding: initial;
font-family: inherit;
}

1
投票

正如您在@Developer 的回答中提到的,我可能会对用户输入进行 HTML 编码。如果您担心 XSS,您可能永远不需要用户以其原始形式输入,所以您不妨转义它(并在您使用它时替换空格和换行符)。

请注意,在输入时转义意味着您应该使用 @Html.Raw 或创建 MvcHtmlString 来呈现该特定输入。

你也可以试试

System.Security.SecurityElement.Escape(userInput)

但我认为它也不会逃脱空间。所以在那种情况下,我建议只做一个 .NET

System.Security.SecurityElement.Escape(userInput).Replace(" ", "&nbsp;").Replace("\n", "<br>")

用户输入。 如果您想更深入地了解可用性,也许您可以对用户输入进行 XML 解析(或使用正则表达式)以仅允许一组预定义的标签。 例如,允许

<p>, <span>, <strong>

...但不允许

<script> or <iframe>

0
投票

这是一个更好的解决方案:

$("div").each(function() {
    var $this = $(this);
    $this.html($this.html().replace(/&nbsp;/g, '<br/>'));
});

-3
投票

有一个简单的方法可以做到这一点。我在我的应用程序上试过了,效果很好。

只需输入:$text = $row["text"]; echo nl2br($文本);

© www.soinside.com 2019 - 2024. All rights reserved.