drupal-javascript について
Drupal 開発者向けの JavaScript リファレンススキルです。モジュールのビヘイビアや AJAX を扱い、ライブラリ定義、Drupal behaviors、設定値の参照、JavaScript と PHP によるカスタム AJAX コマンドを説明します。
主な機能
- 01JavaScript と CSS ライブラリの定義
- 02Twig テンプレートからのライブラリ追加
- 03`once` を使った Drupal behaviors
- 04`drupalSettings` の値の参照
- 05標準およびカスタム AJAX コマンドの実装
活用シーン
- 01Drupal モジュールへの再利用可能な JavaScript と CSS の追加
- 02ビヘイビアによる要素の重複処理の防止
- 03カスタムコマンドを使った AJAX レスポンスの構築
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ edutrul/ drupal-ai --skill drupal-javascriptインストール後、Claude Code で/drupal-javascriptを入力して読み込まれたか確認します。
同梱ファイルREADME.md
詳細
Drupal JavaScript
ライブラリの定義(*.libraries.yml)
# my_module.libraries.yml
my-behavior:
version: 1.0
js:
js/my-behavior.js: {}
css:
component:
css/my-style.css: {}
dependencies:
- core/drupal
- core/jquery
- core/once
Drupal ビヘイビアパターン
// js/my-behavior.js
(function (Drupal, once) {
'use strict';
Drupal.behaviors.myBehavior = {
attach(context, settings) {
// Use `once` to prevent double-processing
once('my-behavior', '.my-selector', context).forEach(function (element) {
// Process element
element.addEventListener('click', function (e) {
e.preventDefault();
// Handle click
});
});
},
detach(context, settings, trigger) {
// Clean up if needed (e.g., 'unload' trigger)
},
};
}(Drupal, once));
Twig でのライブラリのアタッチ
Twig テンプレートから JavaScript/CSS ライブラリをアタッチします。
{{ attach_library('my_module/my-behavior') }}
JS からの drupalSettings へのアクセス
Drupal.behaviors.myBehavior = {
attach(context, settings) {
const myKey = settings.myModule?.key;
if (myKey) {
console.log('Value:', myKey);
}
},
};
PHP からの AJAX コマンド
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Ajax\InvokeCommand;
use Drupal\Core\Ajax\HtmlCommand;
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand('#wrapper', $build));
$response->addCommand(new HtmlCommand('#message', $this->t('Done!')));
$response->addCommand(new InvokeCommand('.my-class', 'addClass', ['active']));
return $response;
カスタム AJAX コマンド
// Register command
Drupal.AjaxCommands.prototype.myCommand = function (ajax, response, status) {
document.querySelector(response.selector).textContent = response.data;
};
// PHP side
use Drupal\Core\Ajax\CommandInterface;
final class MyCommand implements CommandInterface {
public function __construct(
private readonly string $selector,
private readonly string $data,
) {}
public function render(): array {
return [
'command' => 'myCommand',
'selector' => $this->selector,
'data' => $this->data,
];
}
}
カスタム Drupal AJAX コマンド
次の要素を使用してカスタム AJAX コマンドを作成する場合は、このパターンを使用してください。
Drupal.AjaxCommands.prototype- 対応する PHP
CommandInterfaceクラス - AJAX レスポンスで返されるカスタムコマンド名
これは一般的なフォームの AJAX コールバックではなく、新しい AJAX コマンドタイプを定義するためのものです。
コメント
Markdown 対応