Integrating HTMX with Astro is a straightforward process. We start with a default Astro project and proceed to integrate HTMX.
Adding htmx to Astro
First, we need to include the HTMX script in our project:
- Insert HTMX Script Tag: In the layout file, within the
<head>
section, paste the HTMX script tag. This is crucial for enabling HTMX functionality.
Setting Up an Unordered List with htmx in Astro
Next, we focus on the index.astro
page:
- Create an Unordered List: Here, we add an
<ul>
tag. - Configure HTMX Attributes:
- HX Get: Set to
/partials/products/list
. This specifies the resource to fetch. - HX Trigger: Set to
load
. This ensures the GET request triggers when the page loads.
- HX Get: Set to
Upon initial setup, a 404 error will occur, indicating missing partials:
- Create Required Directories and Files: In the file tree, add
partials/products
folders and alist.astro
file. - Configure the List File:
- Export Const Partial: Set
export const partial = true
inlist.astro
. This tells Astro that the file is a partial containing HTML, not a full page. - Add List Items: In the template section of
list.astro
, add several list items (e.g., List 1, List 2, etc.).
- Export Const Partial: Set
With this complete we can see htmx successfully returning a list.