Ease into htmx with htmx-get

Waylon Walker - Mar 25 '22 - - Dev Community

I recently attended python web conf 2022 and after seeing some incredible presentations on it I am excited to give htmx a try.

The base page

Start with some html boilerplate, pop in a script tag to add the htmx.org script, and a button that says click me. I added just a tish of style so that it does not sear your delicate developer your eyes.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title></title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
      html  { background: #1f2022; color: #eefbfe; font-size: 64px; }
      button {font-size: 64px;}
      body { height: 100vh; width: 100vw; display: flex; justify-content: center; align-items:center; }
    </style>
    <!-- Load from unpkg -->
    <script src="https://unpkg.com/htmx.org@1.7.0"></script>
  </head>
  <body>
  <!-- have a button POST a click via AJAX -->
  <button hx-get="/partial" hx-swap="outerHTML">
    Click Me
  </button>

  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Save this as index.html and fire up a webserver and you will be presented with this big beefcake of a button.

big beefcake of a button

If you don't have a development server preference I reccomend opening the terminal and running python -m http.server 8000 then opening your browser to localhost:8000

The Partial

Now the page has a button that is ready to replace itself, notice the
hx-swap="outerHTML">, with the contents of /partial. To create a
static api of sorts we can simply host a partial page in a file at
/partial/index.html with the following contents.

<p>
hello
</p>
Enter fullscreen mode Exit fullscreen mode

the final results

Tree

To make it a bit clearer here is what the file tree looks like after setting this up.

~/git/htmx  v3.9.7 (git)
❯ tree
.
├── clicked
│   └── index.html
└── index.html
Enter fullscreen mode Exit fullscreen mode

Demo

I added htmx to this page and setup a partial below, check out this easter egg.


Click Me

Links

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .