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.
getConfig
option of the class that creates the plugin. See "Color Button": cgit.drupalcode.org/colorbutton/tree/src/Plugin/CKEditorPlugin/…