What The Htmx!
3 months ago
No, HTMX is not a dirty version of HTML.

Once upon a time, while down the youtube tech rabbit hole, I came across a video by Maximilian Schwarzmüller, referring to some dark and disturbing magic called htmx that claimed to reduce if not remove your requirement to write javascript.

Well actually, htmx gives you access to AJAX, CSS Transitions, WebSockets and Server Sent Events directly in HTML, using attributes.

Of course, if you have used Symfony recently, you'll be aware of Hotwire's Turbo, Frames and Stimulus, which is fantastic. But what really struck me about htmx, is the ease of use and concise and practical syntax. 

Sound too good to be true? Well let's have a look, to install simply include the script tag, I did this inside of my `app.js`

<script src="https://unpkg.com/[email protected]"></script>

What about npm or yarn?

npm install htmx.org

yarn add htmx.org

If you are using asset mapper

bin/console importmap:require htmx.org

then import the package inside you `app.js` like so 

import 'htmx.org';


Like an accredited certificate of village idiot, how can we use this practically? 

<div hx-post="{{ path('example_path') }}" hx-trigger="mouseenter">
    [Here Mouse, Mouse!]
</div>

in the controller:


#[Route(path: '/event-list', name: 'event_list')]
public function list(): Response
{
    $events = $this->eventRepository->findAll();
    return $this->render('event/list.html.twig',[
        'events' => $events
    ]);
}

and finally inside of `list.html.twig`

<div class="w-48 text-sm font-medium text-gray-900 bg-white border border-gray-200 rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white">
    {% for event in events %}
        <div class="w-full px-4 py-2 border-b border-gray-200 rounded-t-lg dark:border-gray-600">
            <div>{{ event.title }}</div>
        </div>
    {% endfor %}
</div>

Hover of the mouseover div we created in the first example... That was easy! 


Ok, but wait, we need a loading spinner to indicated it's loading.


add the following css to the `app.css`

.htmx-indicator{
    display:none;
}
.htmx-request .htmx-indicator{
    display:inline;
}
.htmx-request.htmx-indicator{
    display:inline;
}


update the mouseover div:


<div hx-post="{{ path('event_list') }}" hx-trigger="mouseenter">

    <div class="htmx-indicator" role="status">
        <svg aria-hidden="true" class="w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-blue-600" viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="currentColor"/>
            <path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentFill"/>
        </svg>
        <span class="sr-only">Loading...</span>
    </div>

    [Here Mouse, Mouse!]
</div>

Mouseover again... Jesus, mother Mary and Joseph! That's ridiculous. 


Ok, ok, let's calm down a little and increase the complexity. Let's create an instant search. 

First update the `event_list` endpoint:


#[Route(path: '/event-list', name: 'event_list')]
public function list(Request $request): Response
{
    $keyword = $request->get('q');
    $events = $this->eventRepository->findByKeyword(keyword: $keyword);
    return $this->render('event/list.html.twig',[
        'events' => $events
    ]);
}

business as usual inside of the EventRepository, findByKeyword method:


/**
 * @param string $keyword
 * @return array<int, Event>
 */
public function findByKeyword(string $keyword): array
{
    $qb = $this->createQueryBuilder('event');
    $qb->andWhere(
        $qb->expr()->like($qb->expr()->lower('event.title'), ':keyword')
    )->setParameter('keyword', '%' . strtolower($keyword) . '%');

    return $qb->getQuery()->getResult();
}
 

let's repalce our mouseover div with the and input and output: 

<input type="text" name="q"
       hx-get="{{ path('event_list') }}"
       hx-trigger="keyup delay:500ms changed"
       hx-target="#search-results"
       placeholder="Search..."
>
<div id="search-results"></div>

Type something into the text input... This feels illegal.


In my experience the majority of website and applications don't need the monstrous strength of  React or contemporary JS frontend frameworks. Because let's be honest, most projects just don't have the feature requirement.
This package is narrowing the gap between the backend and frontend and it does it so simply and eloquently.

If you are using PHPstorm like me, then you can install the HTML Support plugin which will give you attribute autocompletion, just to make your life that little bit easier.

I was speaking to a ex-colleague and dare I say friend, Fabricio and I theorised about the two problems that plague contemporary programming being firstly, the ever growing gap between the frontend and backend and secondly technical bloating, with the advent of frontend frameworks and HTTP/3, our software has become big, like really big. instead of one framework we now generally have 2, Two nearly completely separate systems, which increases complexity by a considerable degree.

But imagine if you can, a framework that was both frontend and backend simultaneously, where there was no gap between frontend and backend, no JSON tokens. A framework where you can access the browsers information (like timezone) anywhere.  Where the functionality of htmx would be built in, by default.
Now that is pretty cool!