编辑器按钮 (XTD) 插件
本部分介绍如何开发编辑器 XTD 插件。
插件的工作原理如下:插件在 onEditorButtonsSetup
事件中注册一个编辑器按钮,然后系统将根据表单中编辑器字段的配置方式来使用它。
此组中的事件:
onEditorButtonsSetup
onEditorButtonsSetup
每次渲染编辑器时都会触发此事件。
事件签名
function onEditorButtonsSetup(Joomla\CMS\Event\Editor\EditorButtonsSetupEvent $event){}
事件属性
/**
* @var Joomla\CMS\Editor\Button\ButtonsRegistry $subject
* @var array $disabledButtons List of disabled button names
* @var string $editorType Editor type
* @var integer $asset Optional id of Asset, for access check
* @var integer $author Optional id of Author, for access check
*/
$subject = $event->getButtonsRegistry();
$disabled = $event->getDisabledButtons();
$editorType = $event->getEditorType();
$asset = $event->getAsset();
$author = $event->getAuthor();
创建编辑器按钮 (xtd) 插件
以下示例假设您已经知道如何创建 Joomla 插件。
在示例中,我们创建了两个按钮,它们将 🍺 和 🐈 插入到编辑器中。第一个按钮将使用预定义的 insert
操作,第二个按钮将使用我们自定义的操作来执行相同的操作。
首先,在 plugins/editors-xtd/example/
文件夹下创建一个插件,将其命名为 example
,假设命名空间为 JoomlaExample\Plugin\EditorsXtd\Example
。
然后在 onEditorButtonsSetup
事件处理程序中设置按钮。
namespace JoomlaExample\Plugin\EditorsXtd\Example\Extension;
use Joomla\CMS\Editor\Button\Button;
use Joomla\CMS\Event\Editor\EditorButtonsSetupEvent;
use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\Event\SubscriberInterface;
final class Example extends CMSPlugin implements SubscriberInterface
{
/**
* Returns an array of events this subscriber will listen to.
*
* @return array
*/
public static function getSubscribedEvents(): array
{
return ['onEditorButtonsSetup' => 'onEditorButtonsSetup'];
}
/**
* @param EditorButtonsSetupEvent $event
* @return void
*/
public function onEditorButtonsSetup(EditorButtonsSetupEvent $event)
{
$subject = $event->getButtonsRegistry();
$disabled = $event->getDisabledButtons();
if (!\in_array('example-beer', $disabled)) {
$button1 = new Button('example-beer', [
'text' => 'Insert 🍺'
'icon' => 'file-add',
'action' => 'insert', // Action already provided by Joomla.EditorButton
], [
'content' => '🍺', // Content to insert
]);
$subject->add($button1);
}
if (!\in_array('example-cat', $disabled)) {
// Register script with our custom action
$this->getApplication()->getDocument()->getWebAssetManager()
->registerScript(
'editor-button.example-cat',
'plg_editors_xtd_example/example-cat.js',
[],
['type' => 'module'],
['editors']
);
$button2 = new Button('example-cat', [
'text' => 'Insert 🐈'
'icon' => 'file-add',
'action' => 'insert-cat', // Custom action, will code it later
]);
$subject->add($button2);
}
}
}
现在创建一个 JavaScript 使 insert-cat
操作生效。在 media/plg_editors_xtd_example/js/example-cat.js
下创建一个 JavaScript 文件,并在 JoomlaEditorButton
中为 insert-cat
操作注册处理程序
// Import required components
import { JoomlaEditorButton } from 'editor-api';
// Insert 🐈 on cursor
JoomlaEditorButton.registerAction('insert-cat', (editor, options) => {
editor.replaceSelection('🐈');
});
一切都完成了 🎉 插件安装并启用后,按钮应该可用并执行其工作。