问题描述
如何在网页上显示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适当的版本中,必须要转义一些字符:
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.)
当然,您应该在<pre><code>…</code></pre>
中包围生成的,转义的HTML代码,以(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.
所有其他解决方案,例如将代码包装到<textarea>
或(已弃用的)<xmp>
元素中,会破坏 .
All other solutions, such as wrapping your code into a <textarea>
or the (deprecated) <xmp>
element, will break.
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.
例子:
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代码段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!