Установка визуального редактора CKEditor. Настройка CKEdit или как убрать лишние значки на панели Подключение ckeditor

По моему мнению, CKEditor – один из лучших wysiwyg редакторов для сайтов. Последнее время в нем появилось много зауми для упрощения жизни пользователя, в итоге мешающей, например ACF. Как его редактировать и отключать я уже . Но вернемся к теме нашей статьи как установить плагины на CKEditor.

Я вижу здесь два подхода.

Первый – заходим на сайт редактора и пересобираем CKeditor под себя, включая необходимые для нас плагины. Делается это следующим образом. Заходим на сайт ckeditor.com, переходим на вкладку download. Далее выбираем Or let me customize CKEditor


Но в данном случае отображаются не все плагины. Чтобы включить какие-то новые или особенные плагины в сборку, необходимо собирать свою сборку несколько иначе. Заходим в пункт Add-ons ->Plug-ins и видим справа следующую двигающееся меню


При нажатии на кнопку add to my editor плагин добавляется в сборку. По окончании нажимаем Build my editor и заменяем наш встроенный на сайт редактор сгенерированным.

Второй подход для тех, кому самому интересно поковыряться в коде.

На сайте ckeditor.com переходим в раздел add-ons->plug-ins и нажимаем на необходимом плагине.


Выбираем Download и следуем инструкциям с сайта. В большинстве своем они либо сводятся к тому, что нужно установить зависимости к данному плагину и прописать и сам плагин в поле конфигурационного файла config.js и плагин, от которого зависит устанавливаемый через запятую, например,

Config.extraPlugins = "codemirror,youtube,imagerotate";

CKEditor это готовый для использования текстовый рекдактор HTML, созданный для упрощения создания содержания веб страниц. Это WYSIWYG редактор который предоставляет функции редактирования текста непосредственно вашим веб страницам.

CKEditor это приложение с открытым исходным кодом, то есть оно может быть измнено по вашему желанию. Его полезность приходит от активного общества, которое не прекращает развитие приложений с бесплатными add-ons и прозрачным процессом развития (transparent development process).

3- Download CKEditor

У вас есть 4 варианта скачивания CKEditor .

Результат скачивания:

Можете посмотреть примеры CKEditor в папке samples :

4- Базовые примеры:

Все примеры данной статьи содержатся в папке samples в CKEditor который вы скачали. Но я попытаюсь сделать это легче чтобы вам далось легче.

Создать папку myexamples , примеры данной статьи будут находиться в этой папке.

4.1- Заменить элементы Textarea используя JavaScript

Простой пример использование CKEditor.replace(..) чтобы заменить через CKEditor .

replacebycode.html

Replace Textarea by Code Replace Textarea Elements Using JavaScript Code

Hello CKEditor

CKEDITOR.replace("editor1");

Смотрите пример:

Результаты запуска примера:

4.2- Заменить элементы textarea классом name

С имеющие атрибут name, и class ="ckeditor" будет автоматически заменен CKEditor-ом .

Text

replacebyclass.html

Replace Textareas by Class Name Replace Textarea Elements by Class Name

Hello CKEditor

Запуск примера:

4.3- Создать CKEditor с jQuery

Пример создания CKEditor используя JQuery .

jQuery Adapter — CKEditor Sample $(document).ready(function() { $("#editor1").ckeditor(); }); function setValue() { $("#editor1").val($("input#val").val()); } Create Editors with jQuery

Hello CKEditor

As you can see, configurations are set by a simple JavaScript object passed to the create() method.

Removing features

Builds come with all features included in the distribution package enabled by default. They are defined as plugins for CKEditor.

In some cases, you may need to have different editor setups in your application, all based on the same build. For that purpose, you need to control the plugins available in the editor at runtime.

In the example below Heading and Link plugins are removed:

// Remove a few plugins from the default setup. ClassicEditor .create(document .querySelector("#editor" ), { removePlugins : [ "Heading" , "Link" ], toolbar : [ "bold" , "italic" , "bulletedList" , "numberedList" , "blockQuote" ] }) .catch(error => { console .log(error); });

Be careful when removing plugins from CKEditor builds using config.removePlugins . If removed plugins were providing toolbar buttons, the default toolbar configuration included in a build will become invalid. In such case you need to provide the updated toolbar configuration as in the example above.

List of plugins

Each build has a number of plugins available. You can easily list all plugins available in your build:

ClassicEditor.builtinPlugins.map(plugin => plugin.pluginName);

Adding features Adding complex features

As CKEditor builds do not include all possible features, the only way to add more features to them is to create a custom build .

Adding simple (standalone) features

There is an exception to every rule. Although it is impossible to add plugins that have dependencies to @ckeditor/ckeditor5-core or @ckeditor/ckeditor5-engine (that includes nearly all existing official plugins) without rebuilding the build, it is still possible to add simple, dependency-free plugins.

import ClassicEditor from "@ckeditor/ckeditor5-build-classic" ; function MyUploadAdapterPlugin ( editor ) { editor.plugins.get("FileRepository" ).createUploadAdapter = function ( loader ) { // ... }; } // Load the custom upload adapter as a plugin of the editor. ClassicEditor .create(document .querySelector("#editor" ), { extraPlugins : [ MyUploadAdapterPlugin ], // ... }) .catch(error => { console .log(error); }); Toolbar setup

In builds that contain toolbars an optimal default configuration is defined for it. You may need a different toolbar arrangement, though, and this can be achieved through configuration.

Each editor may have a different toolbar configuration scheme, so it is recommended to check its documentation. In any case, the following example may give you a general idea:

ClassicEditor .create(document .querySelector("#editor" ), { toolbar : [ "bold" , "italic" , "link" ] }) .catch(error => { console .log(error); });

The above is a strict UI-related configuration. Removing a toolbar item does not remove the feature from the editor internals. If your goal with the toolbar configuration is to remove features, the right solution is to also remove their respective plugins. Check above for more information.

Listing available items

You can use the following snippet to retrieve all toolbar items available in your editor:

Array .from(editor.ui.componentFactory.names());

На своем сайте использовал BUEditor – простой удобный редактор, но для пользователей он не очень удобен. Часто думал поставить CKEditor, но он мне казался каким-то монстром, но на деле все оказалось не так страшно.

Как установить модуль читаем .

После подключения через свой модуль, на странице admin/config/content/ckeditor/edit/назнание_профиля во вкладке ВНЕШНИЙ ВИД РЕДАКТОРА , в разделе Плагины появится чекбокс активации. Включаем, сохраняем, проверяем.

3. Вставка ссылок. Из коробки диалоговое окно вставки ссылок содержит кучу не нужного и не понятного. Заменяем его плагином Simple link . Как устанавить, смотрим в п.2 . Подключаем (см. п.1) :

Config.extraPlugins = "SimpleLink";

Так же появится новая иконка(кнопка) плагина.

4. Вставка изображений. Здесь все тоже самое, что и ссылками, можно поставить плагин Simple Image для вставки изображений по ссылке.

Config.extraPlugins = "SimpleImage";

Или загружать изображения с помощью модуля One Click Upload. . Подробнее читаем . Я остановился на втором способе, хотя в BUEditor’е использовал оба.

Единственное что хочу добавить, плагин Enhanced Image требует еще два плагина Widget и Lineutils .

не мог понять, почему не запускается плагин, пока не заглянул в журнал

5. Внешний вид. По умолчанию используется скин Moono, я же хотел привести внешность к виду BUEditor’а.

так выглядел BUEditor

7. Placeholder. Чтобы добать placeholder устанавливаем плагин (см. п.2) Configuration Helper . Подключаем (см. п.1) :

Config.extraPlugins = "confighelper"; config.placeholder = "Наш текст"; // текст нашего placeholder

8. Смайлы. За смайлы в CKEditor"e отвечает плагин Insert Smiley , он в ходит в стандартный пакет - Full Package.

Так выгледят смайлы из коробки:

Чтобы заменить их на свои необходимо в конфиге(см. п.1) указать путь до папки с изображениями smiley_path :

Config.smiley_path = "/sites/default/files/smileys/";

Прописать имена файлов (изображений), которые будут отображаться smiley_images :

Config.smiley_images = ["smile_1.png","smile_2.png"];

И description (описание при наведении) smiley_descriptions

Config.smiley_descriptions = ["description-1", "description-2"];

Так же можно указат во сколько колонок выводить смайлы (по умолчанию: 8) smiley_columns

Config.smiley_columns = 6;

Вот что у меня получилось

9. Проверка орфографии браузером. Как написал UksusoFF в CKEditor"е отключена браузерная проверка орфографии. Для того, чтобы отключить это отключение (немного тавтологии), необходимо прописать в конфиге:

Config.disableNativeSpellChecker = false;

10. Контекстное меню. В CKEditor"е, при нажатии ПКМ открывается контекстное меню, а не нативное меню браузера

Download options

There are several options to download CKEditor 5 builds:

After downloading the editor jump to the Basic API guide to see how to create editors.

CDN

Builds can be loaded inside pages directly from , which is optimized for worldwide super fast content delivery. When using CDN no download is actually needed.

npm

All builds are released on npm. Use this search link to view all official build packages available in npm.

Installing a build with npm is as simple as calling one of the following commands in your project:

Npm install --save @ckeditor/ckeditor5-build-classic # Or: npm install --save @ckeditor/ckeditor5-build-inline # Or: npm install --save @ckeditor/ckeditor5-build-balloon # Or: npm install --save @ckeditor/ckeditor5-build-balloon-block # Or: npm install --save @ckeditor/ckeditor5-build-decoupled-document

CKEditor will then be available at node_modules/@ckeditor/ckeditor5-build-/build/ckeditor.js . It can also be imported directly to your code by require("@ckeditor/ckeditor5-build-") .

Zip download

Go to the and download your preferred build. For example, you may download the ckeditor5-build-classic-1.0.0.zip file for the Classic editor build.

Extract the .zip file into a dedicated directory inside your project. It is recommended to include the editor version in the directory name to ensure proper cache invalidation once a new version of CKEditor is installed.

Included files
  • ckeditor.js – The ready-to-use editor bundle, containing the editor and all plugins.
  • ckeditor.js.map – The source map for the editor bundle.
  • translations/ – The editor UI translations (see Setting UI language).
  • README.md and LICENSE.md
Loading the API

After downloading and installing a CKEditor 5 build in your application, it is time to make the editor API available in your pages. For that purpose, it is enough to load the API entry point script:

Once the CKEditor script is loaded, you can