0

I need to show source code examples in a static HTML document. Usually I'd have to escape all occurrences of < > and & to see the code in the browser as intended. Which makes it very hard to write and update. But then I remembered there was that CDATA thing. So I went on and tried it out. But it didn't work, in Firefox and Chrome. The content seems to be parsed and interpreted, not rendered verbatim.

Am I doing it wrong? Am I too late and has the browser support for CDATA disappeared already? Did I misinterpret the documentation? How can I get this to work?

<pre><code><![CDATA[<html>
<input type="text" disabled>Test &amp; more</p>
]]></code></pre>

This shows up as: (with an input box)

[________________]Test & more

]]>
ygoe
  • 18,655
  • 23
  • 113
  • 210
  • Bottom line: No. CDATA is primarily for XML. HTML and XML both started out in life as SGML, and both support [CDATA sections](https://stackoverflow.com/a/3302679/421195). Prior to the current W3C standard, there was a move to "formalize" HTML as XML (the W3C XHTML standard). But currently, for HTML 5, you should NOT use CDATA. Look at this thread for more discussion: https://stackoverflow.com/a/3302679/421195 – paulsm4 Apr 13 '22 at 01:17

2 Answers2

2

From your own CDATA link:

Note: CDATA sections should not be used within HTML they are considered as comments and not displayed.

From the HTML standard:

CDATA sections can only be used in foreign content (MathML or SVG).

Rob
  • 14,746
  • 28
  • 47
  • 65
  • I'll post-process them with JavaScript anyway for syntax highlighting. I just need a way to actually include the raw code content in the HTML with minimal escaping. And, "not displayed" definitely doesn't correspond to my observation. So that documentation seems to be wrong in at least two ways. – ygoe Apr 12 '22 at 23:27
  • @ygoe That document was written by the Firefox people and possibly by Google and Microsoft. I don't think it's going to be too wrong. Note, also, that CDATA is for XML, not HTML in the first place. Also, see my edit. – Rob Apr 13 '22 at 01:07
0

Do not use CDATA. Better solutions are:

  • use online tools for escaping HTML entities automatically.

  • Keep the code on github and link to the repo/file. You can even link to specific line numbers

  • There are libraries for code highlighting on the web like higlight.js

  • Use a js snippet to escape the HTML entities:

function escapeHtml(unsafe)
{
    return unsafe
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;")
         .replace(/(?:\r\n|\r|\n)/g, '<br>');
 }
let code = `
<div class="testdiv">
    test HTML.<br/> 
    <span>More html tags</span>
</div>
`

document.getElementById('code_example').innerHTML = escapeHtml(code)
<div id="code_example"></div>
Eriks Klotins
  • 4,042
  • 1
  • 12
  • 26