Logo Drupal Htmx

Drupal Htmx

Cộng đồng
edutrul
drupal-htmx

HTMX trong core Drupal 11.3+ — trình tạo fluent Htmx PHP, biểu mẫu động với swapOob, routes từng phần với _htmx_route, header phản hồi và tích hợp Drupal.behaviors. Dùng khi xây dựng giao diện tương tác không cần tải lại toàn bộ trang bằng hỗ trợ HTMX tích hợp sẵn của Drupal.

Add to TypingMind

Tổng quan

Nhà phát hànhedutrul
Kho mãdrupal-ai
Tên kỹ năngdrupal-htmx
Sao
73
Bản fork
14
Tệp đi kèm
Chỉ có hướng dẫn
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI dùng hướng dẫn viết bằng Markdown thay vì mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Hướng dẫn có đủ mọi thứ cần thiết

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được edutrul công bố trên GitHub. Hãy đọc các tệp nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Drupal Htmx trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL của thư mục kỹ năng được hiển thị bên dưới rồi xác nhận.
    https://github.com/edutrul/drupal-ai/tree/main/.claude/skills/drupal-htmx
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/edutrul/drupal-ai.git /tmp/drupal-ai
mkdir -p .claude/skills
cp -r /tmp/drupal-ai/.claude/skills/drupal-htmx .claude/skills/drupal-htmx
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Drupal Htmx trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự nạp Drupal Htmx ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên bạn có thể dùng Drupal Htmx với cả những mô hình khác ngoài mô hình ban đầu. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên khi kỹ năng chưa được dùng, bạn không tốn token cho phần hướng dẫn.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Drupal HTMX

HTMX 2.0.4 ships in Drupal 11.3+ core as core/htmx. No contrib module needed.

When to use HTMX vs AJAX Form API

ScenarioUse
Form fields that update other fieldsHTMX (swapOob)
Simple form submit with partial page updateHTMX or AJAX Form API
Complex multi-step AJAX with AjaxResponse commandsAJAX Form API
Non-form UI interactions (lazy load, infinite scroll, boost)HTMX
Existing forms you're modifyingAJAX Form API (less disruption)

Attaching the Library

yaml
# mymodule.libraries.yml
mymodule/htmx-feature:
  dependencies:
    - core/drupal.htmx

core/drupal.htmx includes: htmx vendor JS + Drupal behaviors bridge + asset loader + drupalSettings integration.

The Htmx PHP Fluent Builder

php
use Drupal\Core\Htmx\Htmx;
use Drupal\Core\Url;

$htmx = new Htmx();
$htmx->post($url)->target('#my-wrapper')->swap('outerHTML');
$htmx->applyTo($element);

applyTo() writes data-hx-* attributes directly onto the render array element. Pass '#wrapper_attributes' as second argument to target the wrapper div instead.

php
$htmx->applyTo($form['field'], '#wrapper_attributes');

Request Attributes

php
$htmx->get(?Url $url)          // data-hx-get
$htmx->post(?Url $url)         // data-hx-post
$htmx->put(?Url $url)
$htmx->patch(?Url $url)
$htmx->delete(?Url $url)
$htmx->target('#selector')     // data-hx-target
$htmx->swap('outerHTML')       // data-hx-swap: innerHTML|outerHTML|beforebegin|afterbegin|beforeend|afterend|delete|none
$htmx->swapOob('true')         // data-hx-swap-oob: out-of-band swap
$htmx->select('css selector')  // data-hx-select: pick part of response
$htmx->selectOob(['#id:outerHTML']) // data-hx-select-oob
$htmx->trigger('click')        // data-hx-trigger
$htmx->vals(['key' => 'val'])  // data-hx-vals: extra POST values
$htmx->boost()                 // data-hx-boost: SPA-like link/form enhancement
$htmx->confirm('Are you sure?')
$htmx->on('click', 'alert()')  // data-hx-on:click
$htmx->pushUrl(true)           // data-hx-push-url
$htmx->onlyMainContent()       // adds data-hx-drupal-only-main-content (triggers HtmxRenderer)

Response Headers (applied to render array, sent with response)

php
$htmx->pushUrlHeader($url)                  // HX-Push-Url
$htmx->redirectHeader($url)                 // HX-Redirect
$htmx->triggerHeader('myEvent')             // HX-Trigger (also accepts array with data)
$htmx->triggerAfterSettleHeader('myEvent')  // HX-Trigger-After-Settle
$htmx->refreshHeader(true)                  // HX-Refresh
// Also: replaceUrlHeader, locationHeader, reswapHeader, retargetHeader, reselectHeader, triggerAfterSwapHeader

Pattern: Dependent Selects (Dynamic Forms)

A select that updates another select without page reload. Each field posts to <current> with swapOob so both fields re-render out-of-band.

php
public function buildForm(array $form, FormStateInterface $form_state, string $type = '', string $value = ''): array {
  $formUrl = Url::fromRoute('<current>');

  $form['type'] = [
    '#type' => 'select',
    '#options' => ['a' => 'A', 'b' => 'B'],
    '#default_value' => $type,
  ];
  (new Htmx())->post($formUrl)->swap('none')->swapOob('true')->applyTo($form['type']);

  $form['value'] = [
    '#type' => 'select',
    '#options' => $this->getOptionsFor($form_state->getValue('type', $type)),
    '#default_value' => $value,
  ];
  (new Htmx())->post($formUrl)->swap('none')->swapOob('true')->applyTo($form['value']);

  // Optionally push URL on change:
  $trigger = $form_state->getUserInput()['_triggering_element_name'] ?? FALSE;
  if ($trigger) {
    (new Htmx())->pushUrlHeader(Url::fromRoute('mymodule.form', [...]))->applyTo($form[$trigger]);
  }

  return $form;
}

public function submitForm(array &$form, FormStateInterface $form_state): void {}

Pattern: Partial Route (_htmx_route)

A route that returns only its content fragment (no <html> shell). Use for controllers responding to HTMX hx-get/hx-post calls.

yaml
# mymodule.routing.yml
mymodule.htmx_partial:
  path: '/htmx/content/{id}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\HtmxController::content'
    _title: 'Content'
  options:
    _htmx_route: true   # Uses HtmxRenderer — returns HTML fragment only
  requirements:
    _permission: 'access content'
    id: '\d+'
php
// Controller returns a render array normally — HtmxRenderer handles the rest.
public function content(int $id): array {
  $node = $this->entityTypeManager->getStorage('node')->load($id);
  return [
    '#theme' => 'mymodule_content_card',
    '#node' => $node,
    '#cache' => ['tags' => $node->getCacheTags()],
  ];
}

Pattern: onlyMainContent() — Drupal Layout Bypass

Add data-hx-drupal-only-main-content to any HTMX element. The Drupal JS bridge automatically appends ?_wrapper_format=drupal_htmx to the request, triggering HtmxRenderer (no page chrome, no blocks, no regions).

php
$htmx = new Htmx();
$htmx->get($url)->onlyMainContent()->target('#content-area')->applyTo($element);

Alternatively add the attribute directly in Twig:

twig
<a href="{{ path('mymodule.page') }}"
   data-hx-get="{{ path('mymodule.page') }}"
   data-hx-drupal-only-main-content
   data-hx-target="#content-area">
  Load content
</a>

Pattern: Boost (SPA-like Navigation)

Apply hx-boost to a container and all links/forms inside become AJAX-driven, replacing <body> and updating <title>. Drupal's Drupal.behaviors re-attaches automatically on each swap.

php
$form['#attributes']['data-hx-boost'] = 'true';
// or via Htmx builder:
(new Htmx())->boost()->applyTo($form);

Pattern: Lazy Loading / Infinite Scroll

twig
{# Load content when element scrolls into view #}
<div data-hx-get="{{ path('mymodule.more_items', {page: page}) }}"
     data-hx-trigger="revealed"
     data-hx-swap="outerHTML">
  <div class="loading-spinner">{{ 'Loading...'|t }}</div>
</div>

Pattern: Confirm Before Action

php
(new Htmx())
  ->delete(Url::fromRoute('mymodule.delete', ['id' => $id]))
  ->target('#item-' . $id)
  ->swap('outerHTML')
  ->confirm((string) $this->t('Delete this item?'))
  ->applyTo($form['delete_button']);

Pattern: Trigger Custom JS Event from Response

php
// In controller or form, trigger a JS event after swap:
(new Htmx())
  ->triggerAfterSettleHeader('mymodule:itemUpdated')
  ->applyTo($element);
javascript
// In your Drupal behavior:
Drupal.behaviors.mymoduleListener = {
  attach(context) {
    context.addEventListener('mymodule:itemUpdated', (e) => {
      // React to HTMX-triggered event
    });
  }
};

Drupal.behaviors Integration

No extra setup needed. The core/drupal.htmx library auto-wires:

  • htmx:drupal:load → calls Drupal.attachBehaviors() on swapped content
  • htmx:drupal:unload → calls Drupal.detachBehaviors() before swap

All existing JS behaviors work transparently on HTMX-injected content.

drupalSettings in HTMX Responses

drupalSettings from HTMX responses is deep-merged into the current page's drupalSettings automatically by htmx-utils.js. No action needed.

Detecting HTMX Requests in PHP

php
use Symfony\Component\HttpFoundation\Request;

// Check if request is from HTMX
$isHtmx = $request->headers->has('HX-Request');
$trigger = $request->headers->get('HX-Trigger-Name'); // triggering element name
$currentUrl = $request->headers->get('HX-Current-URL');

Cache Considerations

HTMX partial responses go through Drupal's render cache normally. Apply cache metadata as usual:

php
return [
  '#theme' => 'mymodule_partial',
  '#cache' => [
    'tags' => ['node:' . $node->id()],
    'contexts' => ['url.query_args'],
    'max-age' => 0, // for frequently-changing content
  ],
];

HtmxRenderer adds the rendered cache tag and required cache contexts automatically.

Twig — Attaching HTMX Attributes

twig
{# Attach htmx library #}
{{ attach_library('mymodule/htmx-feature') }}

{# Render an element with htmx attributes (set via PHP Htmx builder) #}
{{ content.my_field }}

{# Or write attributes directly in Twig #}
<button data-hx-post="{{ path('mymodule.action') }}"
        data-hx-target="#result"
        data-hx-swap="innerHTML">
  {{ 'Submit'|t }}
</button>

Always use data-hx-* (not bare hx-*) — Drupal's implementation uses the data- prefix convention.

Routing for Forms with HTMX

Route parameters from the URL are passed to buildForm() as extra arguments:

yaml
mymodule.form:
  path: '/mymodule/form/{type}/{value}'
  defaults:
    _form: '\Drupal\mymodule\Form\DependentSelectForm'
    _title: 'My Form'
    type: ''
    value: ''
  requirements:
    _permission: 'access content'
php
public function buildForm(array $form, FormStateInterface $form_state, string $type = '', string $value = ''): array {

Common Mistakes

Missing library: HTMX attributes render as static HTML without core/drupal.htmx attached. Always attach in libraries.yml or #attached.

Using bare hx-*: Drupal uses data-hx-*. The Htmx builder adds the data- prefix automatically. In Twig, write data-hx-get not hx-get.

Forgetting swap('none') on oob triggers: When using swapOob, the trigger element itself also gets swapped unless you set swap('none').

CSRF on POST: Drupal's Form API handles CSRF tokens. For non-form HTMX POSTs to controllers, add the route requirement _csrf_token: 'TRUE' and append ?token={{ drupal_csrf_token(...) }} to the URL.

Raw markup for target placeholders: Never use #markup to render a standalone HTMX target div — it bypasses Drupal's render pipeline. Use #type => 'html_tag' with #attributes instead:

php
// Bad
'target' => ['#markup' => '<div id="greeting-target"></div>'],

// Good
'target' => [
  '#type' => 'html_tag',
  '#tag' => 'div',
  '#value' => '',
  '#attributes' => ['id' => 'greeting-target'],
],

If the target can be the wrapper of an existing render element, skip the separate div and use applyTo() with '#wrapper_attributes' plus an #attributes['id'] on that element instead.

Câu hỏi thường gặp

Kỹ năng AI Drupal Htmx làm được gì?

HTMX trong core Drupal 11.3+ — trình tạo fluent Htmx PHP, biểu mẫu động với swapOob, routes từng phần với _htmx_route, header phản hồi và tích hợp Drupal.behaviors. Dùng khi xây dựng giao diện tương tác không cần tải lại toàn bộ trang bằng hỗ trợ HTMX tích hợp sẵn của Drupal.

Vì sao nên dùng Drupal Htmx trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Drupal Htmx là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Drupal Htmx trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/edutrul/drupal-ai/tree/main/.claude/skills/drupal-htmx. TypingMind đọc tệp SKILL.md rồi cài đặt kỹ năng để bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Drupal Htmx?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Có thể dùng Drupal Htmx với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Drupal Htmx với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Drupal Htmx có miễn phí không?

Có. Kỹ năng này được edutrul phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp các công cụ mới mà mô hình có thể gọi. Khi mô hình gọi một công cụ, mã của công cụ đó chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và những tiêu chí mà kết quả cần đáp ứng. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇