Tip

Return HTML from the Backend with Astro Partials and htmx

Return HTML from the backend with htmx and Astro partials

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:

  1. 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:

  1. Create an Unordered List: Here, we add an <ul> tag.
  2. 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.
<ul hx-get="/partials/products/list" hx-trigger="load"></ul>

Upon initial setup, a 404 error will occur, indicating missing partials:

  1. Create Required Directories and Files: In the file tree, add partials/products folders and a list.astro file.
  2. Configure the List File:
    • Export Const Partial: Set export const partial = true in list.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 = true;
<li>list 1</li>
<li>list 2</li>
<li>list 3</li>
<li>list 4</li>

With this complete we can see htmx successfully returning a list.