Search code examples
htmlpre

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


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

     <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 two versions of the same code, one escaped and one not escaped.

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, maybe in HTML5?

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

The JavaScript solution does not work on Firefox 21, here is a screenshot:

screenshot of non-working code

The first solution still does not work on Firefox, here is a screenshot:

screenshot of HTML code


Solution

  • You can use the xmp element, 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).

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

    Otherwise xmp is rendered like 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 xmp is 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 pre element:

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

    I don’t see how you could combine xmp and CDATA section to achieve so-called polyglot markup