Is there a way to show HTML code-snippets on a webpage without needing to replace each < with <
and > with >
?
In other words, is there some tag which simply says "Don't render html until you hit the closing tag?"
Is there a way to show HTML code-snippets on a webpage without needing to replace each < with <
and > with >
?
In other words, is there some tag which simply says "Don't render html until you hit the closing tag?"
You can use a CDATA section:
<![CDATA[Your <code> here]]>
Only “disadvantage”: it doesn’t work reliably in all browsers (last time I checked). So it’s essentially a no-go.
EDIT Only works in X(HT)ML, not in HTML itself, since it’s defined in XML rather than SGML.
There are a few ways to escape everything in HTML, none of them nice.
Or you could put in an iframe
that loads a plain old text file.
Depreciated, but works in FF3 and IE8.
<xmp>
<b>bold</b><ul><li>list item</li></ul>
</xmp>
Recommended:
<pre><code>
code here, escape it yourself.
</code></pre>
The deprecated xmp tag essentially does that but is no longer part of the XHTML spec. It should still work though in all current browsers.
If it's just to display the content, you could enclose the entire thing in a textarea like so:
<textarea disabled="true" style="border: none;background-color:white;">
<p>test</p>
</textarea>
If you want it to be non-editable and look different then you could easily style it using CSS. The only issue would be that browsers will add that little drag handle in the bottom-right corner to resize the box. Or alternatively, try using an input tag instead.
Other than that, the only way is really to escape the code yourself if static HTML or using server-side methods such as .NET's HtmlEncode() if using such technology.
Ultimately the best (though annoying) answer is "escape the text".
There are however a lot of text editors -- or even stand-alone mini utilities -- that can do this automatically. So you never should have to escape it manually if you don't want to (Unless it's a mix of escaped and un-escaped code...)
Quick Google search shows me this one, for example: http://malektips.com/zzee-text-utility-html-escape-regular-expression.html