mcpField
D
drupal-javascript

drupal-javascript

github.com/edutrul开发7351 次安装21 周前更新
代码仓库

关于 drupal-javascript

面向 Drupal 开发者的 JavaScript 参考技能,介绍模块行为和 AJAX 交互。内容涵盖库定义、Drupal behaviors、设置读取,以及 JavaScript 与 PHP 配合实现自定义 AJAX 命令。

主要功能

  1. 01定义 JavaScript 和 CSS 库
  2. 02从 Twig 模板附加库
  3. 03使用 `once` 编写 Drupal behaviors
  4. 04读取 `drupalSettings` 中的值
  5. 05实现标准及自定义 AJAX 命令

适用场景

  1. 01为 Drupal 模块添加可复用的 JavaScript 和 CSS
  2. 02避免行为代码重复处理页面元素
  3. 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 Behavior 模式

// 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