Reputation: 20393
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 & more</p>
]]></code></pre>
This shows up as: (with an input box)
[________________]Test & more
]]>
Upvotes: 0
Views: 206
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, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'")
.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
Reputation: 15168
From your own CDATA link:
Note: CDATA sections should not be used within HTML they are considered as comments and not displayed.
CDATA sections can only be used in foreign content (MathML or SVG).
Upvotes: 2