1

I saw that we can pass values to our JavaScript using drupalSettings. However, this is for Drupal custom module JavaScript files. Since a CKEditor plugin file is already attached/loaded in a different way, I am wondering what's the correct way to pass variables to it.

The following is the code that I made, according to the example, but I have the feeling that plugin.js is loaded two times:

  • one time in inline_comment_preprocess_html()
  • and one more time with inline_comment/src/Plugin/CKEditorPlugin/InlineComment.php

What's the correct way to pass variables to plugin.js?

inline_comment.info.yml

name: CKEditor Inline Comment
type: module
description: "Adds the Inline Comment plugin to CKEditor."
package: CKEditor

dependencies:
  - ckeditor
  - core/jquery
  - core/drupalSettings

version: '8.x-1.0'
core: '8.x'
project: 'inline_comment'

inline_comment.module

function inline_comment_preprocess_html(&$variables) {
  $lotus_height = '300px';
  $variables['#attached']['library'][] = 'js/plugins/inline_comment/plugin.js'; // I think I shouldn't try to load plugin.js two times
  $variables['#attached']['drupalSettings']['lotus']['lotusJS']['lotus_height'] = $lotus_height;

}

js/plugins/inline_comment/plugin.js

CKEDITOR.plugins.add('inline_comment', {
    //...
});

(function ($, Drupal, drupalSettings) {
    Drupal.behaviors.LotusBehavior = {
        attach: function (context, settings) {
            var lotusHeight = drupalSettings.lotus.lotusJS.lotus_height;
            console.log('lotusHeight' + lotusHeight);
        }
    };
})(jQuery, Drupal, drupalSettings);

I noticed if I remove the line with $variables['#attached']['library'][] and I dump($variables) there is no drupalSettings variable in #attached array.

2

1 Answer 1

1

You can pass options via getConfig option of the class that creates the plugin. See how the module "Color Button" does it:

https://cgit.drupalcode.org/colorbutton/tree/src/Plugin/CKEditorPlugin/ColorButton.php?h=8.x-1.x

This is passed along to the defined plugin when it is loaded up (the one defined in getFile.)

See: https://api.drupal.org/api/drupal/core%21modules%21ckeditor%21src%21CKEditorPluginBase.php/class/CKEditorPluginBase/8.6.x

and:

https://api.drupal.org/api/drupal/core%21modules%21ckeditor%21src%21CKEditorPluginInterface.php/function/CKEditorPluginInterface%3A%3AgetConfig/8.6.x

The variable names passed or modified in getConfig need to be the same names as the ones in the plugin to be overwritten.

1
  • I would just add that if you're working in a custom ckeditor plugin that the variables are available in editor.config after being added through this method.
    – ummdorian
    Commented May 4, 2021 at 1:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.