Load an HTML Partial in Astro using HTMX

Zac Jones
author
Zac Jones
Published
8 months ago

Integrating HTMX with Astro is a straightforward process. We start with a default Astro project and proceed to integrate HTMX.

You can create an Astro project by running yarn create astro.

Adding HTMX to Astro

In your Layout.astro file, include a script tag that brings in HTMX from unpkg.

<head>
...
<script src="https://unpkg.com/htmx.org@1.9.9"></script>
</head>

Setting Up an Unordered List with HTMX in Astro

In pages/index.astro you can use hx-get and a relative route to get the HTML from a partial file.

Use the hx-trigger attribute with a value of load to trigger the GET request on page load. Add these attributes to an unordered list (ul) tag.

<Layout title="Welcome to Astro">
<main>
<h1>Astro x htmx</h1>
<ul
hx-get="/partials/products/list"
hx-trigger="load"
></ul>
</main>
</Layout>

After setting that up, you'll need to create the partial file pages/partials/products/list.astro.

In list.astro, you need to tell astro that a partial file is not a page using the following syntax at the top of the file. Make sure to include the ---:

---
export const partial = true
---

Then you can add the HTML partial that you want to be loaded

---
export const partial = true
---
<li>list 1</li>
<li>list 2</li>
<li>list 3</li>
<li>list 4</li>

Conclusion

And voilà! You should now be getting the HTML from your partial loaded onto the page.

The sky's the limit really with this pattern. You get to create reusable HTML components without bringing in a big JavaScript framework of any kind.

Check out a video version of this article in this tip -> https://egghead.io/tips/return-html-from-the-backend-with-astro-partials-and-htmx