ygoe
ygoe

Reputation: 20393

Can I use CDATA for content in modern HTML?

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

]]>

Upvotes: 0

Views: 206

Answers (2)

Eriks Klotins
Eriks Klotins

Reputation: 4180

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>

Upvotes: 0

Rob
Rob

Reputation: 15168

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).

Upvotes: 2

Related Questions