在 HTML 中显示 HTML 片段 [英] Display HTML snippets in HTML
问题描述
如何在网页上显示 HTML 片段而不需要将每个 <
替换为 <
并将 >
替换为 <代码>>?
How can I show HTML snippets on a webpage without needing to replace each <
with <
and >
with >
?
换句话说,是否有一个标签在你点击结束标签之前不要渲染 HTML?
In other words, is there a tag for don't render HTML until you hit the closing tag?
推荐答案
是否有在点击结束标记之前不呈现 HTML 的标记?
不,没有.在 HTML 中,转义一些字符是必不可少的:
No, there is not. In HTML proper, there’s no way short of escaping some characters:
&
为&
<
为<
&
as&
<
as<
(顺便说一句,没有必要逃避>
,但人们经常出于对称的原因这样做.)
(Incidentally, there is no need to escape >
but people often do it for reasons of symmetry.)
当然,您应该将生成的转义 HTML 代码括在 <pre><code>...</code></pre>
中以 (a) 保留空格和行中断,并且 (b) 将其标记为代码元素.
And of course you should surround the resulting, escaped HTML code within <pre><code>…</code></pre>
to (a) preserve whitespace and line breaks, and (b) mark it up as a code element.
所有其他解决方案,例如将您的代码包装到 或(已弃用)
元素中,将中断.1
All other solutions, such as wrapping your code into a <textarea>
or the (deprecated) <xmp>
element, will break.1
以 XML 形式向浏览器声明的 XHTML(通过 HTTP Content-Type
标头!—仅设置 DOCTYPE
是不够) 也可以使用 CDATA 部分:
XHTML that is declared to the browser as XML (via the HTTP Content-Type
header! — merely setting a DOCTYPE
is not enough) could alternatively use a CDATA section:
<![CDATA[Your <code> here]]>
但这仅适用于 XML,不适用于 HTML,甚至这也不是万无一失的解决方案,因为代码不能包含结束分隔符 ]]>
.因此,即使在 XML 中,最简单、最可靠的解决方案也是通过转义.
But this only works in XML, not in HTML, and even this isn’t a foolproof solution, since the code mustn’t contain the closing delimiter ]]>
. So even in XML the simplest, most robust solution is via escaping.
1 例子:
textarea {border: none; width: 100%;}
<textarea readonly="readonly">
<p>Computer <textarea>says</textarea> <span>no.</span>
</textarea>
<xmp>
Computer <xmp>says</xmp> <span>no.</span>
</xmp>
这篇关于在 HTML 中显示 HTML 片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!