我想创建一个用户可以将其插入到编辑器中的元素。 困难的部分是它需要以不同于其来源的方式显示。 例如,我想让用户在预览部分插入这个:
23
在源代码部分应该这样显示:
<span class="tagSpecialClass">{{birthYear}}</span>
主要目的是以用户可以避免编写它们的方式显示 mustache 标签,只需从自动插入正确 html 并预览到它的工具栏插入它们。
我的问题是我对 CKEditor 的理解以及我需要阅读的条款以实现这样的插件。
如何强制 CKEditor 以不同方式解析/编译/预览特定标签?
如果我的问题太笼统,请告诉我!
最佳答案
这听起来像是 CKEditor widgets 的工作(demos)!
请看下面的例子(JSFiddle)。它会给你一些基本的想法,如何使用小部件来解决你的问题。如果关注this official tutorial ,您将了解如何在小部件中实现可编辑部分以及如何使用对话框进行编辑,这也可能会有帮助。
// Some CSS for the widget to make it more visible.
CKEDITOR.addCss( '.tagSpecialClass { background: green; padding: 3px; color: #fff } ' );
CKEDITOR.replace( 'editor', {
// A clean-up in the toolbar to focus on essentials.
toolbarGroups: [
{ name: 'document', groups: [ 'mode' ] },
{ name: 'basicstyles' },
{ name: 'insert' }
],
removeButtons: 'Image,Table,HorizontalRule,SpecialChar',
extraPlugins: 'widget',
on: {
pluginsLoaded: function() {
var editor = this;
// Define a new widget. This should be done in a separate plugin
// to keep things clear and maintainable.
editor.widgets.add( 'sampleWidget', {
// This will be inserted into the editor if the button is clicked.
template: '<span class="tagSpecialClass">23</span>',
// A rule for ACF, which permits span.tagSpecialClass in this editor.
allowedContent: 'span(tagSpecialClass)',
// When editor is initialized, this function will be called
// for every single element. If element matches, it will be
// upcasted as a "sampleWidget".
upcast: function( el ) {
return el.name == 'span' && el.hasClass( 'tagSpecialClass' );
},
// This is what happens with existing widget, when
// editor data is returned (called editor.getData() or viewing source).
downcast: function( el ) {
el.setHtml( '{{birthYear}}' );
},
// This could be done in upcast. But let's do it here
// to show that there's init function, which, unlike
// upcast, works on real DOM elements.
init: function() {
this.element.setHtml( '23' );
}
} );
// Just a button to show that "sampleWidget"
// becomes a command.
editor.ui.addButton && editor.ui.addButton( 'SampleWidget', {
label: 'Some label',
command: 'sampleWidget',
toolbar: 'insert,0'
} );
}
}
} );
HTML
<textarea id="editor">
<p>Some text.</p>
<p>And there's the widget <span class="tagSpecialClass">{{birthYear}}</span></p>
<p>Some text <span class="tagSpecialClass">{{birthYear}}</span>.</p>
</textarea>
编码愉快!
关于javascript - CKEditor:如何在预览中以不同方式显示代码块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23566729/