ckeditor是一个非常好用的在线富文本编辑器,但是由于其不自带代码高亮,所以需要我们自己添加代码高亮。官方给出的方法是在ckeditor/plugins中注册插件,由于现在版本的ckeditor已经自带代码高亮插件,于是可以直接注册,具体教程网上都有,但是按照官网注册后编辑框并不能自动显示出,添加代码的图标,我发现还是需要手动添加,网上很多教程都已经过时了,我现在来做一份最新的ckeditor代码高亮插件,添加教程;
一、方法:
(1)在ckeditor/config.js中,添加
config.extraPlugins: "codesnippet";
来注册这个插件
(2)在项目的settings.py中添加:
CKEDITOR_CONFIGS = {
'default': {
'toolbar': (['div', 'Source', '-', 'Save', 'NewPage', 'Preview', '-', 'Templates'],
['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-','Print','SpellChecker','Scayt'],
['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat','-','Maximize', 'ShowBlocks', '-',"CodeSnippet", 'Subscript', 'Superscript'],
['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton',
'HiddenField'],
['Bold', 'Italic', 'Underline', 'Strike', '-'],
['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote'],
['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
['Link', 'Unlink', 'Anchor'],
['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak'],
['Styles', 'Format', 'Font', 'FontSize'],
['TextColor', 'BGColor'],
),
'extraPlugins': 'codesnippet',
}
}
(3)大功告成
二、网上教程失效原因
新注册的插件并不会自动添加,需要手动在设置中添加按钮,按钮的名称要与在对应插件plugin.js中注册的按钮名称一样,如果不一样,就会出现按钮无法显示的问题。网上的其他教程中,出现的注册按钮名为codesnippet,而实际上我阅读源码后得知,在插件中,注册的名字是CodeSnippet同理,如果其他插件的按钮无法显示可以考虑相同问题。
三、js中添加按钮的代码解释:
(function () {
b = 'format_wz';
CKEDITOR.plugins.add(b, {
requires: ['styles', 'button'],
init: function (a) {
a.addCommand(b, CKEDITOR.plugins.autoformat.commands.autoformat);
//按钮名称,在toolbar注册时必须保持名字与这里一致
a.ui.addButton('format_wz', {
//鼠标移上去的提示
label: "一键排版",
command: 'format_wz',
//图标
icon: this.path + "format_wz.png"
});
}
});
CKEDITOR.plugins.autoformat = {
commands: {
autoformat: {
exec: function (editor) {
formatText(editor);
}
}
}
};