ikellenberger ikellenberger - 3 months ago 31x
HTML Question

Tags Get Removed When Using Codesample Plugin with TinyMCE

Since 4.3.0 TinyMCE includes Codesample plugin that lets you enter code snippets.
This works very well for languages like Java, PHP, C# etc. that are not directly running in the browser. You save your code snippet to the server, load it back into the browser, edit it, and save it back to the server again - no hassle.

If you want to do it with HTML, JavaScript, or XML, then it seems not to be possible to load the code snippet back into the browser after saving it to the server.
Most of the tags will be removed, despite being already encoded before.

See TinyMCE Fiddle 1 and TinyMCE Fiddle 2 that try to illustrate the problem.

Any ideas? Many thanks in advance!


If you want to reload content into TinyMCE that was previously stored in your database I would use TinyMCE's JavaScript APIs to load the data after the editor is initialized. I have created a fiddle to show how you would do this.


In this example the content that would have come out of TinyMCE from a prior edit is in the theContent variable:

var theContent = '<pre class="language-markup"><code>&lt;ul&gt;&lt;li&gt;one&lt;/li&gt;&lt;li&gt;two&lt;/li&gt;&lt;/ul&gt;</code></pre>';

(In a real application you would of course grab this from the database and inject it into the web page instead of hard coding the value)

I then use the TinyMCE API for setContent to add the content to TinyMCE once its loaded:

setup: function (editor) {
    editor.on('init', function () {
    var theContent = '<pre class="language-markup"><code>&lt;ul&gt;&lt;li&gt;one&lt;/li&gt;&lt;li&gt;two&lt;/li&gt;&lt;/ul&gt;</code></pre>';

When you do it this way the editor will properly syntax highlight the code sample content (as seen in the Fiddle).

<textarea> tags and HTML are a difficult combination if you have anything beyond the simplest of HTML so I would avoid dropping HTML directly into the <textarea>.