在转义的 html 中呈现换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12694110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rendering newlines in escaped html
提问by Yarin
We have a display message that is auto-generated by default, but may be overridden by GET vars from the url. Since we need to treat the message as user input, it must be escaped for display. However, we want to retain the ability to include newlines.
我们有一个默认自动生成的显示消息,但可能会被来自 url 的 GET 变量覆盖。由于我们需要将消息视为用户输入,因此必须对其进行转义以显示。但是,我们希望保留包含换行符的能力。
Newlines as <br>
This won't work because escaping HTML destroys the <br>
tag.
Newlines as<br>
这将不起作用,因为转义 HTML 会破坏<br>
标记。
Newlines as \n
I can't figure out how to get \n
to render as newlines. I thought putting it in a tag would render correctly, but no luck: http://jsfiddle.net/7L932/
\n
换行符,因为
我不知道如何\n
渲染为换行符。我认为将它放在标签中会正确呈现,但没有运气:http: //jsfiddle.net/7L932/
采纳答案by Michael Krelin - hacker
What you're doing is more or less fine, except for you should put \n
character (newline), not the escape sequence in your html (and what Prinzhorn says also makes perfect sense, so I'll go upvote him).
你所做的或多或少是好的,除了你应该\n
在你的html中输入字符(换行符),而不是转义序列(Prinzhorn所说的也很有意义,所以我会去给他投票)。
回答by Prinzhorn
Escape the HTML, and thenreplace \n
with <br>
.
转义 HTML,然后替换\n
为<br>
.
In case you want to use \n, I fix your fiddle for you http://jsfiddle.net/hr3bg/
如果您想使用 \n,我会为您修复您的小提琴http://jsfiddle.net/hr3bg/
回答by Barney
Your theory's sound, but \n
is a not an HTML-recognised way of inserting a new line. It either comes in explicitly (as I've inserted in a new .linebreaks
element) as a literal return in the markup, or, if you're using some intermediary scripting language that doesrecognise \n
(like JS), do that (as I've done to your first .linebreaks
with the jQuery code I inserted.
您的理论听起来不错,但\n
不是 HTML 认可的插入新行的方式。它要么显式地(因为我已经插入一个新.linebreaks
元素)作为标记中的文字返回,或者,如果您使用一些可以识别的中间脚本语言\n
(如 JS),请这样做(因为我已经.linebreaks
用我插入的 jQuery 代码完成了你的第一个工作。
See my tweak to your example: http://jsfiddle.net/barney/7L932/2/
请参阅我对您的示例的调整:http: //jsfiddle.net/barney/7L932/2/