htmx/www/official-extensions.md

4.0 KiB

layout title
layout.njk </> htmx - high power tools for html

Official Extensions

The following extensions are tested against htmx and thus are considered officially supported.

debug

Description

This extension includes log all htmx events for the element it is on with the "DEBUG:" prefix.

Usage

<button hx-ext="debug">Debug Me...</button>

Source

htmx.defineExtension('debug', {
    onEvent : function(name, evt) {
        if(console.debug){
            console.debug(name, evt);
        } else if(console) {
            console.log("DEBUG:", name, evt);
        } else {
            throw "NO CONSOLE SUPPORTED"
        }
    }
});

rails-method

Description

This extension includes the rails _method parameter in non-GET or POST requests.

Usage

<body hx-ext="rails-method">
 ...
</body>

Source

htmx.defineExtension('rails-method', {
    onEvent : function(name, evt) {
        if(name === "configRequest.htmx"){
            var methodOverride = evt.detail.headers['X-HTTP-Method-Override'];
            if(methodOverride){
                evt.detail.parameters['_method'] = methodOverride;
            }
        }
    }
});

morphdom-swap

Description

This extension allows you to use the morphdom library as the swapping mechanism in htmx.

Usage

<header>
  <script src="lib/morphdom-umd.js"></script> <!-- include the morphdom library -->
</header>
<body hx-ext="morphdom-swap">
   <button hx-swap="morphdom">This button will be swapped with morphdom!</button>
</body>

Source

htmx.defineExtension('morphdom-swap', {
    handleSwap : function(swapStyle, target, fragment) {
        if (swapStyle === 'morphdom') {
            morphdom(target, fragment.outerHTML);
            return []; // no settle phase when using morphdom!
        }
    }
});

json-enc

Description

This extension encodes parameters in JSON format instead of url format.

Usage

<div hx-post='/test' hx-ext='json-enc'>click me</div>

Source

htmx.defineExtension('json-enc', {
    encodeParameters : function(xhr, parameters, elt) {
        xhr.requestHeaders['Content-Type'] = 'application/json';
        xhr.overrideMimeType('text/json');
        return (JSON.stringify(parameters));
    }
});

client-side-templates

Description

This extension supports transforming a JSON request response into HTML via a client-side template before it is swapped into the DOM. Currently three client-side templating engines are supported:

When you add this extension on an element, any element below it in the DOM can use one of three attributes named <template-engine>-temlpate (e.g. mustache-template) with a template ID, and the extension will resolve and render the template the standard way for that template engine:

  • mustache - looks a mustache