将 Codesample 插件与 TinyMCE 一起使用时标签被删除

Tags Get Removed When Using Codesample Plugin with TinyMCE

从 4.3.0 开始,TinyMCE 包含可让您输入代码片段的 Codesample 插件。 这对于 Java、PHP、C# 等不直接在浏览器中 运行 的语言非常有效。您将代码片段保存到服务器,将其加载回浏览器,对其进行编辑,然后再次将其保存回服务器 - 没有麻烦。

如果您想使用 HTML、JavaScript 或 XML 执行此操作,则似乎无法在保存后将代码片段加载回浏览器它到服务器。 大多数标签将被删除,尽管之前已经编码。

参见 TinyMCE Fiddle 1 and TinyMCE Fiddle 2 试图说明问题。

有什么想法吗?非常感谢!

如果您想将之前存储在数据库中的内容重新加载到 TinyMCE 中,我会在编辑器初始化后使用 TinyMCE 的 JavaScript APIs 加载数据。我创建了一个 fiddle 来展示您将如何执行此操作。

http://fiddle.tinymce.com/50faab/3

在这个例子中,先前编辑的 TinyMCE 的内容在 theContent 变量中:

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>';

(在实际应用程序中,您当然会从数据库中获取它并将其注入网页,而不是对值进行硬编码)

然后我将 TinyMCE API 用于 setContent,以便在加载内容后将内容添加到 TinyMCE:

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>';
        this.setContent(theContent);
    });
}

当您这样做时,编辑器将正确地语法突出显示代码示例内容(如 Fiddle 中所示)。

<textarea> 标签和 HTML 是一个困难的组合,如果你有任何超出最简单的 HTML 的东西,所以我会避免将 HTML 直接放入 <textarea>.

Felix Riesterer 在 forum of TinyMCE 中的回答也可能有帮助:

Yes, in the way I pointed out: < > and " need to be properly encoded as < > and " because these characters have a special meaning in HTML context. So if you want to comply with the specs (and TinyMCE expects you to do so!) you need to convert these characters accordingly. There is no way around that.

And yes, I forgot to mention that & (ampersand) needs to be encoded as & as well.

You might have to double-encode stuff: If you want to see "" you need to code &lt;h1&gt; so the HTML code renders as plain text. The logic behind it is like this:

1. content gets decoded into raw text (&lt; gets translated to <, &amp; becomes &)

2.raw text gets treated as original HTML code for the editor contents (&lt;h1&gt; renders as <h1>, <h1> renders as a first-level heading)

扩展 Michael 的回答,将您的内容放入隐藏 DIV,然后抓取它 html 对我来说效果更好:

<div class="theDiv">
    <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>
</div>

var theContent = $('.theDiv').html();