Build: Drupal HTMX vs Ajax Replacement Demo
There is a fascinating conversation happening in the Drupal community right now: HTMX Now in Drupal Core. The proposal? To replace the venerable (but aging) jQuery-based Ajax API with a modern, lightweight, HTML-over-the-wire subsystem based on HTMX.
To understand the practical implications, I built a demo module comparing the two approaches side-by-side.
The Experiment
I created drupal-htmx-ajax-replacement-demo, a module that renders two identical interactive cards. One uses the standard Drupal.ajax library, and the other uses HTMX.
1. Legacy Drupal Ajax
The traditional way relies on jQuery and a custom JSON protocol.
The Flow:
- Client clicks a link with
.use-ajax. Drupal.ajaxintercepts the click.- Server builds an
AjaxResponsewith commands (e.g.,ReplaceCommand). - Server returns JSON:
[{"command": "insert", "method": "html", ...}]. - Client Javascript parses JSON and executes DOM manipulation.
The Code:
public function timeAjax() {
$response = new AjaxResponse();
$response->addCommand(new HtmlCommand('#container', $html));
return $response;
}
2. The HTMX Way
HTMX allows us to be declarative. We define what we want in HTML attributes, and the server just returns HTML.
The Flow:
- Client clicks
<button hx-get="..." hx-target="...">. - HTMX intercepts.
- Server returns standard HTML fragment.
- HTMX swaps the HTML into the target.
The Code:
public function time() {
return new Response($html);
}
Why This Matters
The difference in complexity is striking.
- Javascript: The legacy approach requires the heavy
core/drupal.ajaxlibrary (and jQuery). HTMX is lighter and requires no custom Javascript for this interaction. - Backend: The HTMX controller returns a simple
Responseobject with a string. The legacy controller requires instantiatingAjaxResponseand learning theCommandAPI.
You can view the full source code and the comparative implementation in the repository below.
View Code
