edelvalle/djhtmx

Interactive UI components for Django using htmx.org

djhtmx

Interactive UI Components for Django using htmx

Install

Add djhtmx to your INSTALLED_APPS and install the Middleware as the last one of the list:

INSTALLED_APPS = [
    ...
    'djhtmx',
    ...
]

MIDDLEWARE = [
    ...,
    'djhtmx.Middleware',
]

And expose the HTTP endpoint in your urls.py as you wish, you can use any path.

from django.urls import path, include

urlpatterns = [
    # ...
    path('__htmx/', include('djhtmx.urls')),
    # ...
]

In your base template you need to load the necessary scripts to make this work

{% load htmx %}
<!doctype html>
<html>
    <head>
        {% htmx-headers %}
    </head>
</html>

Getting started

This app will look for live.py files in your app and registers all components found there, but if you load any module where you have components manually when Django boots up, that also works.

from djhtmx.component import PydanticComponent


class Counter(PydanticComponent):
    template_name = 'counter.html'
    counter: int = 0

    def inc(self, amount: int = 1):
        self.counter += amount

The counter.html would be:

{% load htmx %}
<div {% hx-tag %}>
  {{ counter }}
  <button {% on 'inc' %}>+</button>
  <button {% on 'inc' amount=2 %}>+2</button>
</div>

Now use the component in any of your html templates:

{% load htmx %} Counter: <br />
{% htmx 'Counter' %} Counter with init value 3:<br />
{% htmx 'Counter' counter=3 %}

Python APIs

TODO

Template tags

TODO

Extended htmx attributes

  • hx-after-swap: Add JavaScript here if you want it to be executed when the element is updated.
Stars
43
100.00% more than last month
Forks
4
Open Issues
5