2014-05-09 33 views
3

我想創建一個元素,用戶可以將它插入到編輯器中。 困難的部分是它需要以不同的來源顯示。 例如,我想用戶在預覽部分插入此:CKEditor:如何在預覽中顯示不同的代碼塊

,並在源部分,應該這個樣子:

<span class="tagSpecialClass">{{birthYear}}</span> 

主要目的是展示鬍鬚標籤的方式,用戶可以避免編寫它們,只需從工具欄中插入它們,即可自動插入正確的html和預覽。

我的問題是我對CKEditor的理解以及爲了實現這樣一個插件我需要閱讀它們的術語。

如何強制CKEditor以不同的方式解析/編譯/預覽特定標籤?

請告訴我,如果我的問題過於通用!

+0

已經有一個插件,基本上做你以後的事情。看看[佔位符插件](http://ckeditor.com/ckeditor_4.3_beta/samples/plugins/placeholder/placeholder.html)。它不會進行文本替換,但會顯示創建標籤的基本思路。 – epascarello

回答

4

這聽起來像是一份工作CKEditor widgetsdemos)!

請看下面的例子(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>  

編碼愉快!