Custom CKEditor Widgets in Drupal 8

Add functionality to the CKEditor

Super easy thanks to Drupal's plugin system!

Define the widget in js

plugin.js


(function ($, Drupal, drupalSettings, CKEDITOR) {
  var WIDGETS = [];
  WIDGETS[0] = {
    details: {
      name: 'Accordion',
      ...
    },
    widget_definition: {
      template: '
' + '
' + '

Title

' + '
' + '

Content...

' + '
', ...

plugin.js (continued)


      ...
      editables: {
        title: {
          selector: '.accordion__title',
          allowedContent: 'h2 h3'
        },
        content: {
          selector: '.accordion__content',
          allowedContent: 'p br ul ol li strong em a[!href,data-*]; img[alt,!src,data-*]'
        }
      },

      allowedContent: 'div(!accordion); div(!accordion__title); div(!accordion__content); div(!details-wrapper)',

      requiredContent: 'div(accordion); div(accordion__title); div(accordion__content)',
          

Tell Drupal about it

my_module/src/Plugin/CKEditorPlugin/EditorWidgets.php


use Drupal\ckeditor\CKEditorPluginBase;

/**
 * Defines the "Editor Widgets" plugin.
 *
 * @CKEditorPlugin(
 *   id = "editor_widgets",
 *   label = @Translation("Editor Widgets")
 * )
 */
class EditorWidgets extends CKEditorPluginBase {

  public function getFile() {
    return drupal_get_path('module', 'my_module') . "/js/editor_widgets/plugin.js";
  }
  ...
          

EditorWidgets.php (continued)


  ...
  public function getButtons() {
    return [
      'editor_widgets' => [
        'label' => t('Editor Widgets'),
        'image_alternative' => [
          '#type' => 'inline_template',
          '#template' => '{{ widgets_text }}',
          '#context' => [
            'widgets_text' => t('Widgets'),
          ],
        ],
      ],
    ];
  }
          

Questions?

PreviousNext Company logo linked to front page