如何在 PRE 或类似的东西中显示原始 html 代码但不转义它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16783708/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 08:48:18  来源:igfitidea点击:

How to display raw html code in PRE or something like it but without escaping it

htmlpre

提问by Robert H

I'd like to display raw HTML. We all know one has to escape each "<" and ">" like this

我想显示原始 HTML。我们都知道必须像这样逃避每个“<”和“>”

     <PRE> this is a test  &ltDIV&gt </PRE>

However, I do not want to do this. I'd like a way to keep the HTML code as is (since it is easier to read, (inside the editor) and I might want to copy it and use it again myself as actual HTML code, and do not want to have to change it again or have 2 versions of the same code one escaped and one not escaped).

但是,我不想这样做。我想要一种保持 HTML 代码原样的方法(因为它更容易阅读,(在编辑器内),我可能想复制它并作为实际的 HTML 代码再次使用它,并且不想不得不再次更改它或具有相同代码的 2 个版本,一个已转义,一个未转义)。

Is there any other environment that is more "raw" than PRE that might allow this? So one does not have to keep editing HTML and changing everything each time they want to show some raw HTML code, may be in HTML5?

有没有其他比 PRE 更“原始”的环境可能允许这样做?因此,人们不必在每次想要显示一些原始 HTML 代码时都继续编辑 HTML 并更改所有内容,可能是在 HTML5 中?

Something like <REALLY_REALLY_VERBATIM> ...... </<REALLY_REALLY_VERBATIM>

就像是 <REALLY_REALLY_VERBATIM> ...... </<REALLY_REALLY_VERBATIM>

screen shot

截屏

The javascript solution does not work on FF 21, here is screen shot enter image description here

javascript 解决方案在 FF 21 上不起作用,这里是屏幕截图 在此处输入图片说明

screen shot 2

屏幕截图 2

The first solution still does not work on firefox, here is screen shot enter image description here

第一个解决方案在 Firefox 上仍然不起作用,这是屏幕截图 在此处输入图片说明

回答by Jukka K. Korpela

You can use the xmpelement, see What was the <XMP> tag used for?. It has been in HTML since the beginning and is supported by all browsers. Specifications frown upon it, but HTML5 CR still describes it and requires browsers to support it (though it also tells authors not to use it, but it cannot really prevent you).

您可以使用该xmp元素,请参阅<XMP> 标签用于什么?. 它从一开始就在 HTML 中,并且被所有浏览器支持。规范不赞成它,但 HTML5 CR 仍然描述它并要求浏览器支持它(虽然它也告诉作者不要使用它,但它不能真正阻止你)。

Everything inside xmpis taken as such, no markup (tags or character references) is recognized there, except, for apparent reason, the end tag of the element itself, </xmp>.

里面的所有东西都是xmp这样的,那里没有任何标记(标签或字符引用)被识别,除了,出于明显的原因,元素本身的结束标签,</xmp>

Otherwise xmpis rendered like pre.

否则xmp呈现为pre.

When using “real XHTML”, i.e. XHTML served with an XML media type (which is rare), the special parsing rules do not apply, so xmpis treated like pre. But in “real XHTML”, you can use a CDATA section, which implies similar parsing rules. It has no special formatting, so you would probably want to wrap it inside a preelement:

当使用“真正的 XHTML”时,即 XHTML 与 XML 媒体类型一起使用(这种情况很少见),特殊的解析规则不适用,因此xmp被视为pre. 但是在“真正的 XHTML”中,您可以使用 CDATA 部分,这意味着类似的解析规则。它没有特殊的格式,所以你可能想把它包装在一个pre元素中:

<pre><![CDATA[
This is a demo, tags like <p> will
appear literally.
]]></pre>

I don't see how you could combine xmpand CDATA section to achieve so-called polyglot markup

我不明白你如何结合xmp和 CDATA 部分来实现所谓的多语言标记

回答by GitaarLAB

Essentially the original question can be broken down in 2 parts:

本质上,原始问题可以分为两部分:

  • Main objective/challenge: embedding(/transporting) a raw formatted code-snippet (any kind of code) in a web-page's markup (for simple copy/paste/edit due to no encoding/escaping)
  • correctly displaying/rendering that code-snippet (possibly edit it) in the browser
  • 主要目标/挑战:在网页的标记中嵌入(/传输)原始格式的代码片段(任何类型的代码)(由于没有编码/转义,用于简单的复制/粘贴/编辑)
  • 在浏览器中正确显示/呈现该代码片段(可能对其进行编辑)

The short (but) ambiguousanswer is: you can't, ...but you can (get very close).
(I know, that are 3 contradicting answers, so read on...)

简短(但)模棱两可的答案是:你不能......但你可以(非常接近)。
(我知道,这是 3 个相互矛盾的答案,所以请继续阅读......)

(polyglot)(x)(ht)ml Markup-languages rely on wrapping (almost) everything between begin/opening and end/closing tags/character(sequences).
So, to embed anykind of raw code/snippet inside your markup-language, one will always have to escape/encode every instance (inside that snippet) that resembles the character(-sequence) that would close the wrapping 'container' element in the markup. (During this post I'll refer to this as rule no 1.)
Think of "some "data" here"or <i>..close italics with '</i>'-tag</i>, where it is obvious one should escape/encode (something in) </iand "(or change container's quote-character from "to ').

(polyglot)(x)(ht)ml 标记语言依赖于包装(几乎)开始/开始和结束/结束标记/字符(序列)之间的所有内容。
因此,要在您的标记语言中嵌入任何类型的原始代码/片段,您将始终必须对每个类似于字符(-sequence)的实例(在该片段内)进行转义/编码标记。(在这篇文章中,我将其称为第 1 条规则。)
想想"some "data" here"or <i>..close italics with '</i>'-tag</i>,很明显应该转义/编码(其中的某些内容)</i"(或将容器的引号字符从 更改"')。

So, because of rule no 1, you can't'just' embed 'any' unknown raw code-snippet inside markup.
Because, if one has to escape/encode even onecharacter inside the raw snippet, then that snippet would no longer be the same original 'pure raw code' that anyone can copy/paste/edit in the document's markup without further thought. It would lead to malformed/illegal markup and Mojibake(mainly) because of entities.
Also, shouldthat snippet contain such characters, you'd stillneed some javascript to 'translate' that character(sequence) from (and to) it's escaped/encoded representation to display the snippet correctlyin the 'webpage' (for copy/paste/edit).

因此,由于规则 1,您不能“只是”在标记中嵌入“任何”未知的原始代码片段。
因为,如果必须对原始片段中的一个字符进行转义/编码,那么该片段将不再是任何人都可以在文档的标记中复制/粘贴/编辑而无需进一步思考的原始“纯原始代码” 。由于实体,它会导致格式错误/非法标记和Mojibake(主要)。
此外,如果该片段包含此类字符,您仍然需要一些 javascript 来“翻译”该字符(序列)从(和到)它的转义/编码表示以正确显示片段在“网页”中(用于复制/粘贴/编辑)。

That brings us to (some of) the datatypes that markup-languages specify. These datatypes essentially define what are considered 'valid characters' and their meaning (per tag, property, etc.):

这将我们带到了标记语言指定的(一些)数据类型。这些数据类型本质上定义了被视为“有效字符”的内容及其含义(每个标签、属性等):

  • PCDATA(Parsed Character DATA): will expand entities and one must escape <, &(and >depending on markup language/version).
    Most tags like body, div, pre, etc, but also textarea(until HTML5) fall under this type.
    So not only do you need to encode all the container's closing character-sequences inside the snippet, you also have to encode all <, &(,>) characters (at minimum).
    Needless to say, encoding/escaping this many characters falls outside this objective's scope of embedding a raw snippet in the markup.
    '..But a textarea seems to work...', yes, either because of the browsers error-engine trying to make something out of it, or because HTML5:

  • RCDATA(Replaceable Character DATA): will not not treat tags inside the text as markup (but are still governed by rule 1), so one doesn't need to encode <(>). BUT entities are still expanded, so they and 'ambiguous ampersands' (&) need special care.
    The currentHTML5 spec says the textarea is now a RCDATAfieldand (quote):

    The text in raw textand RCDATAelements must notcontain any occurrences of the string "</"(U+003C LESS-THAN SIGN, U+002F SOLIDUS) followed by characters that case-insensitively match the tag name of the element followed by one of U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), U+0020 SPACE, U+003E GREATER-THAN SIGN (>), or U+002F SOLIDUS (/).

    Thus no matter what, textarea needs a hefty entity translation handler or it willeventually Mojibake on entities!

  • CDATA(Character Data) will not treat tags inside the text as markup and will not expand entities.
    So as long as the raw snippet code does not violate rule 1 (that one can't have the containers closing character(sequence) inside the snippet), this requires no otherescaping/encoding.

  • PCDATA(Parsed Character DATA): 将扩展实体,必须转义<&>取决于标记语言/版本)。
    大多数标签如bodydivpre等,但也textarea(直到 HTML5)属于这种类型。
    因此,您不仅需要对代码段内所有容器的结束字符序列进行编码<,还必须对所有, &(, >) 字符(至少)进行编码。
    不用说,编码/转义这么多字符超出了在标记中嵌入原始片段的目标范围。
    '..但是一个 textarea 似乎可以工作......',是的,要么是因为浏览器错误引擎试图从中做出一些事情,要么是因为 HTML5:

  • RCDATA(Replaceable Character DATA):不会将文本中的标签视为标记(但仍受规则 1 约束),因此不需要编码<( >)。但是实体仍然被扩展,因此它们和“模棱两可的&符号”(&)需要特别注意。
    目前的HTML5规范说,现在textarea的是RCDATA和(报价):

    raw textRCDATA元素中的文本不得包含任何出现的字符串"</"(U+003C LESS-THAN SIGN, U+002F SOLIDUS) 后跟不区分大小写匹配元素标签名称的字符,后跟 U+0009 CHARACTER TABULATION 之一(tab)、U+000A 换行符 (LF)、U+000C 换页符 (FF)、U+000D 回车符 (CR)、U+0020 空格、U+003E 大于号 (>) 或 U+ 002F SOLIDUS (/)。

    因此,不管是什么,需要的textarea大幅实体翻译处理,或者最终变为乱码的实体!

  • CDATA(Character Data)不会将文本内的标签视为标记,也不会展开实体
    因此,只要原始代码段代码不违反规则 1(代码段内不能有容器关闭字符(序列)),就不需要其他转义/编码。

Clearly this boils down to: how can we minimizethe number of characters/character-sequences that still need to be encoded in the snippet's raw sourceand the number of times that character(sequence) might appear in an average snippet; something that is also of importance for the javascript that handles the translation of these characters (if they occur).

显然,这归结为:我们如何最大限度地减少仍需要在代码段原始源中编码的字符/字符序列的数量以及该字符(序列)可能出现在平均代码段中的次数;这对于处理这些字符的翻译(如果它们发生)的 javascript 也很重要。

So what 'containers' have this CDATAcontext?

那么什么“容器”有这个CDATA上下文呢?

Most value properties of tags are CDATA, so one could(ab)use a hidden input's value property (proof of concept jsfiddle here).
However (conform rule 1) this creates an encoding/escape problem with nested quotes ("and ') in the raw snippet and one needs some javascript to get/translate and set the snippet in another (visible) element (or simply setting it as a text-area's value). Somehow this gave me problems with entities in FF (just like in a textarea). But it doesn't really matter, since the 'price' of having to escape/encode nested quotes is higher then a (HTML5) textarea (quotes are quite common in source code..).

标签的大多数值属性都是 CDATA,因此可以(ab)使用隐藏输入的值属性(此处为概念证明 jsfiddle)。
但是(符合规则 1)这会在原始代码段中使用嵌套引号("')创建编码/转义问题,并且需要一些 javascript 来获取/翻译并将代码段设置在另一个(可见)元素中(或简单地将其设置为文本-区域的值)。不知何故,这给了我 FF 中实体的问题(就像在 textarea 中一样)。但这并不重要,因为必须对嵌套引号进行转义/编码的“价格”高于(HTML5)textarea(引号在源代码中很常见......)。

What about trying to (ab)use <![CDATA[<tag>bla & bla</tag>]]>?
As Jukka points out in his extended answer, this would only work in (rare) 'real xhtml'.
I thought of using a script-tag (with or without such a CDATA wrapper inside the script-tag) together with a multi-line comment /* */that wraps the raw snippet (script-tags can have an idand you can access them by count). But since this obviously introduces a escaping problem with */, ]]>and </scriptin the raw snippet, this doesn't seem like a solution either.

尝试(ab)使用<![CDATA[<tag>bla & bla</tag>]]>怎么样?
正如 Jukka 在他的扩展回答中指出的那样,这只适用于(罕见的)“真正的 xhtml”。
我想过使用脚本标签(在脚本标签内有或没有这样的 CDATA 包装器)以及/* */包装原始片段的多行注释(脚本标签可以有一个id,你可以通过计数访问它们)。但是由于这显然引入了一个转义问题*/]]>并且</script在原始代码段中,这似乎也不是一个解决方案

Please post other viable 'containers' in the comments to this answer.

请在对此答案的评论中发布其他可行的“容器”。

By the way, encoding or counting the number of -characters and balancing them out inside a comment tag <!-- -->is just insane for this purpose (apart from rule 1).

顺便说一句,为此目的(除了规则 1),编码或计算-字符数并在注释标签内平衡它们<!-- -->是很疯狂的。



That leaves us with Jukka K. Korpela's excellent answer: the <xmp>tag seems the best option!

这给我们留下了尤卡K. Korpela的出色答卷<xmp>标签似乎是最好的选择!

The 'forgotten' <xmp>holds CDATA, is intended for this purpose AND is indeed still in the currentHTML 5 spec(and has been at least since HTML3.2); exactly what we need! It's also widely supported, even in IE6 (that is.. until it suffers from the same regression as the scrolling table-body).
Note: as Jukka pointed out, this will not work in true xhtml or polyglot (that will treat it as a pre) and the xmptag must still adhere to rule no 1. But that's the 'only' rule.

在“遗忘”<xmp>CDATA,被用于此目的,确实仍然当前HTML 5规范(和HTML3.2以来已经至少); 正是我们所需要的!它也得到了广泛的支持,即使在 IE6 中也是如此(也就是说......直到它遭受与滚动表体相同的回归)。
注意:正如 Jukka 所指出的,这在真正的 xhtml 或多语言(将其视为pre)中不起作用,并且xmp标签仍必须遵守规则 1。但这是“唯一”规则。

Consider the following markup:

考虑以下标记:

<!-- ATTENTION: replace any occurrence of &lt;/xmp with </xmp -->
<xmp id="snippet-container">
<div>
    <div>this is an example div &amp; holds an xmp tag:<br />
        <xmp> 
<html><head>  <!-- indentation col 0!! -->
    <title>My Title</title>
</head><body>
    <p>hello world !!</p>
</body></html>
        &lt;/xmp>  <!-- note this encoded/escaped tag -->
    </div>
    This line is also part of the snippet
</div>
</xmp>

The above codeblok illustrates a raw piece of markup where <xmp id="snippet-container">contains an (almost raw) code-snippet (containing div>div>xmp>html-document).
Notice the encoded closing tag in this markup? To comply with rule no 1, this was encoded/escaped).

上面的代码块说明了一段原始标记,其中<xmp id="snippet-container">包含一个(几乎原始的)代码片段(包含div>div>xmp>html-document)。
注意到这个标记中编码的结束标记了吗?为了遵守规则 1,这被编码/转义)。

So embedding/transporting the (sometimes almost) raw code is/seems solved.

因此嵌入/传输(有时几乎)原始代码已/似乎已解决。

What about displaying/rendering the snippet (and that encoded &lt;/xmp>)?

显示/呈现代码段(以及已编码的&lt;/xmp>)怎么样?

The browser will (or it should) render the snippet (the contents inside snippet-container) exactlythe way you see it in the codeblock above (with some discrepancy amongst browsers whether or not the snippet starts with a blank line).
That includesthe formatting/indentation, entities (like the string &amp;), full tags, comments AND the encoded closing tag &lt;/xmp>(just like it was encoded in the markup). And depending on browser(version) one could even try use the property contenteditable="true"to edit this snippet (all that without javascript enabled). Doing something like textarea.value=xmp.innerHTMLis also a breeze.

浏览器将(或应该)按照您在上面的代码块中看到的方式完全呈现代码段(其中的内容snippet-container)(无论代码段是否以空行开头,浏览器之间都存在一些差异)。 这包括格式/缩进、实体(如字符串)、完整标签、注释和编码的结束标签(就像在标记中编码一样)。并且根据浏览器(版本),甚至可以尝试使用该属性来编辑此代码段(所有这些都没有启用 javascript)。做类似的事情也是轻而易举的。
&amp;&lt;/xmp>contenteditable="true"textarea.value=xmp.innerHTML

So you can... ifthe snippet doesn't contain the containers closing character-sequence.

所以你可以......如果片段不包含关闭字符序列的容器。

However, shoulda raw snippet contain the closing character-sequence </xmp(because it is an example of xmp itself or it contains some regex, etc), you must accept that you have to encode/escape that sequence in the raw snippet AND need a javascript handler to translate that encoding to display/render the encoded &lt;/xmp>like </xmp>inside a textarea(for editing/posting) or (for example) a prejust to correctly render the snippet's code (or so it seems).

但是如果原始片段包含结束字符序列</xmp(因为它是 xmp 本身的一个例子或者它包含一些正则表达式等),您必须接受必须在原始片段中编码/转义该序列并且需要一个 javascript处理器把这种编码来显示/渲染编码&lt;/xmp></xmp>textarea(编辑/发帖)或(例如)pre只是为了正确渲染片断的代码(或者看起来是这样)。

A very rudimentary jsfiddle example of this here. Note that getting/embedding/displaying/retrieving-to-textarea worked perfect even in IE6. But setting the xmp's innerHTMLrevealed some interesting 'would-be-intelligent' behavior on IE's part. There is a more extensive note and workaround on that in the fiddle.

这里有一个非常基本的jsfiddle 示例。请注意,即使在 IE6 中,获取/嵌入/显示/检索到文本区域也能完美运行。但是设置xmp'sinnerHTML揭示了 IE 方面一些有趣的“将是智能的”行为。在小提琴中有更广泛的注释和解决方法。

But now comes the important kicker(another reason why you only get very close): Just as an over-simplified example, imagine this rabbit-hole:

但现在来了重要的踢球者你只能非常接近的另一个原因):就像一个过于简单的例子,想象一下这个兔子洞

Intended raw code-snippet:

预期的原始代码片段:

<!-- remember to translate between </xmp> and &lt;/xmp> -->
<xmp>
<p>a paragraph</p>
</xmp>

Well, to comply with rule 1, we 'only' need to encode those </xmp[> \n\r\t\f\/]sequences, right?

好吧,为了遵守规则 1,我们“只”需要对这些</xmp[> \n\r\t\f\/]序列进行编码,对吗?

So that gives us the following markup (using just a possible encoding):

因此,这为我们提供了以下标记(仅使用一种可能的编码):

<xmp id="container">
<!-- remember to translate between &lt;/xmp> and &lt;/xmp> -->
<xmp>
<p>a paragraph</p>
&lt;/xmp>
</xmp>

Hmm.. shalt I get my crystal ball or flip a coin? No, let the computer look at its system-clock and state that a derived number is 'random'. Yes, that should do it..

嗯.. 我是拿水晶球还是扔硬币?不,让计算机查看其系统时钟并声明派生数字是“随机”的。是的,应该这样做..

Using a regex like: xmp.innerHTML.replace(/&lt;(?=\/xmp[> \n\r\t\f\/])/gi, '<');, would translate 'back' to this:

使用:xmp.innerHTML.replace(/&lt;(?=\/xmp[> \n\r\t\f\/])/gi, '<');这样的正则表达式会将“返回”转换为:

<!-- remember to translate between </xmp> and </xmp> -->
<xmp>
<p>a paragraph</p>
</xmp>

Hmm.. seems this random generator is broken... Houston..?
Should you have missed the joke/problem, read again starting at the 'intended raw code-snippet'.

嗯.. 似乎这个随机生成器坏了......休斯顿..?
如果您错过了笑话/问题,请从“预期的原始代码片段”开始再次阅读。

Wait, I know, we (also) need to encode .... to ....
Ok, rewind to 'intended raw code-snippet' and read again.
Somehow this all begins to smell like the famous hilarious-but-true rexgex-answer on SO, a good read for people fluent in mojibake.

等等,我知道,我们(也)需要编码 .... 到 ....
好的,回到“预期的原始代码片段”并再次阅读。
不知何故,这一切都开始像SO 上著名的热闹但真实的 rexgex-answer 一样,对于精通mojibake 的人来说,这是一本很好的读物。

Maybe someone knows a clever algorithm or solution to fix this problem, but I assume that the embedded raw code will get more and more obscure to the point where you'd be better of properly escaping/encoding just your <, &(and >), just like the rest of the world.

也许有人知道一个聪明的算法或解决方案来解决这个问题,但我认为嵌入的原始代码会变得越来越模糊,以至于你最好正确地转义/编码你的<, &(和>),就像剩下的世界。

Conclusion:(using the xmptag)

结论:(使用xmp标签)

  • it can be done with known snippets that do not contain the container's closing character-sequence,
  • we can get very close to the original objective with known snippets that only use 'basic first-level' escaping/encoding so we don't fall in the rabbithole,
  • but ultimatelyit seems that one can't do this reliably in a 'production-environment' where people can/should copy/paste/edit 'any unknown' raw snippets while not knowing/understanding the implications/rules/rabbithole (depending on your implementation of handling/translating for rule 1 and the rabbit-hole).
  • 它可以使用不包含容器结束字符序列的已知片段来完成,
  • 我们可以使用仅使用“基本第一级”转义/编码的已知片段来非常接近原始目标,因此我们不会陷入困境,
  • 最终似乎人们无法在“生产环境”中可靠地做到这一点,在这种环境中人们可以/应该复制/粘贴/编辑“任何未知”的原始片段,同时不知道/理解其含义/规则/兔子洞(取决于您的规则 1 和兔子洞的处理/翻译的实现)。

Hope this helps!

希望这可以帮助!

PS: Whilst I would appreciate an upvote if you find this explanation useful, I kind of think Jukka's answer should be the accepted answer (should no better option/answer come along), since he was the one who remembered the xmp tag (that I forgot about over the years and got 'distracted' by the commonly advocated PCDATA elements like pre, textarea, etc.).
This answer originated in explaining why you can't do it (with any unknown raw snippet) and explain some obvious pitfalls that some other (now deleted) answers overlooked when advising a textarea for embedding/transport. I've expanded my existing explanation to also support and further explain Jukka's answer (since all that entity and *CDATA stuff is almost harder than code-pages).

PS:虽然如果你觉得这个解释有用,我会很感激,但我认为 Jukka 的答案应该是公认的答案(不应该有更好的选择/答案出现),因为他是那个记得 xmp 标签的人(我忘了多年来得到了“分心”被普遍提倡PCDATA元素,如pretextarea等)。
这个答案起源于解释为什么你不能这样做(使用任何未知的原始片段)并解释一些明显的陷阱,在建议嵌入/传输的文本区域时,其他一些(现已删除)答案被忽略。我已经扩展了我现有的解释,以支持并进一步解释 Jukka 的答案(因为所有实体和 *CDATA 内容几乎比代码页更难)。

回答by Henry

Cheap and cheerful answer:

便宜又开朗的答案:

<textarea>Some raw content</textarea>

The textarea will handle tabs, multiple spaces, newlines, line wrapping all verbatim. It copies and pastes nicely and its valid HTML all the way. It also allows the user to resize the code box. You don't need any CSS, JS, escaping, encoding.

textarea 将逐字处理制表符、多个空格、换行符、换行。它一直很好地复制和粘贴其有效的 HTML。它还允许用户调整代码框的大小。你不需要任何 CSS、JS、转义、编码。

You can alter the appearance and behaviour as well. Here's a monospace font, editing disabled, smaller font, no border:

您也可以更改外观和行为。这是一个等宽字体,禁用编辑,字体较小,无边框:

<textarea
    style="width:100%; font-family: Monospace; font-size:10px; border:0;"
    rows="30" disabled
>Some raw content</textarea>

This solution is probably not semantically correct. So if you need that, it might be best to choose a more sophisticated answer.

此解决方案在语义上可能不正确。因此,如果您需要,最好选择更复杂的答案。

回答by tribulant

echo '<pre>' . htmlspecialchars("<div><b>raw HTML</b></div>") . '</pre>';

I think that's what you're looking for?

我想这就是你要找的?

In other words, use htmlspecialchars() in PHP

换句话说,在 PHP 中使用 htmlspecialchars()

回答by Jan Turoň

@GitaarLAB and @Jukka elaborate that <xmp>tag is obsolete, but still the best. When I use it like this

@GitaarLAB 和 @Jukka 详细说明该<xmp>标签已过时,但仍然是最好的。当我像这样使用它时

<xmp>
<div>Lorem ipsum</div>
<p>Hello</p>
</xmp>

then the first EOL is inserted in the code, and it looks awful.

然后在代码中插入第一个EOL,它看起来很糟糕

It can be solved by removing that EOL

可以通过删除 EOL 来解决

<xmp><div>Lorem ipsum</div>
<p>Hello</p>
</xmp>

but then it looks bad in the source. I used to solve it with wrapping <div>, but recently I figured out a nice CSS3 rule, I hope it also helps somebody:

但是在源代码中看起来很糟糕。我曾经用 wrapping 解决它<div>,但最近我想出了一个很好的 CSS3 规则,我希望它也能帮助某人:

xmp { margin: 5px 0; padding: 0 5px 5px 5px; background: #CCC; }
xmp:before { content: ""; display: block; height: 1em; margin: 0 -5px -2em -5px; }

This looks better.

看起来更好

回答by CONvid19

xmpis the way to go, i.e.:

xmp是要走的路,即:

<xmp>
  # your code...
</xmp>

回答by PanicBus

If you have jQuery enabled you can use an escapeXml function and not have to worry about escaping arrows or special characters.

如果您启用了 jQuery,您可以使用 escapeXml 函数而不必担心转义箭头或特殊字符。

<pre>
  ${fn:escapeXml('
    <!-- all your code --> 
  ')};
</pre>