Load an HTML Partial in Astro using HTMX
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.
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.
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 ---
:
Then you can add the HTML partial that you want to be loaded
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