Search code examples
htmlescapingckeditorpre

CKEditor escape html


I have CKEditor on post text where I want to insert html-code. Something like this:

<pre>
<code class="html">
<img src="path/to/img.jpg" />
</code>
</pre>

But when I save the text, CKEditor interprets img-tag as actual html-image and shows broken image. How I can prevent that and tell to escape html-code in pre-code block


Solution

  • <pre>
    <code class="html">
    <img src="path/to/img.jpg" />
    </code>
    </pre>
    

    This is an image inside a pre element. What you want to create is:

    <pre>
    <code class="html">
    &lt;img src="path/to/img.jpg" /&gt;
    </code>
    </pre>
    

    And if you write <img .../> inside pre element in CKEditor, then CKEditor will return this (valid) HTML.

    What developers often don't know is that when they load that content from their database into <textarea> this content may need to be encoded (depends on how it's saved). In PHP for instance it's enough to pass it through htmlspecialchars().