Skip to content

htmx + Alpine template tag

I used Alpine’s <template> tag for something on my site, and inside this template tag I used some htmx to power a form.

The template was defined like this:

<template x-if="$store.showModal">
  <form>...</form>
</template>

Problem was, my form only sent GET requests (the default browser behavior) because how template tags work in Alpine is, the HTML is added to the DOM when the template x-if directive resolves to true.

So basically htmx had no idea about this new HTML.

I had to re-process the form by adding an id to the form and then using something like

htmx.process(htmx.find('#form-edit-project-name'))

Where to add this code?

Inside the x-init attribute in the template.

But x-init is ran when the element is processed by Alpine (you can test with x-init="console.log('test')").

You want to check, inside x-init, for when the condition is true, and then run the htmx processing.

Like this:

<template
  x-if="$store.showModal"
  x-init=`
    $watch('$store.showModal', () => {
      if ($store.showModal === true) {
        htmx.process(htmx.find('#form-edit-project-name'))
      }
    })`
>
  <form id="form-edit-project-name">...</form>
</template>

I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter

  • C Handbook
  • Command Line Handbook
  • CSS Handbook
  • Express Handbook
  • Git Cheat Sheet
  • Go Handbook
  • HTML Handbook
  • JS Handbook
  • Laravel Handbook
  • Next.js Handbook
  • Node.js Handbook
  • PHP Handbook
  • Python Handbook
  • React Handbook
  • SQL Handbook
  • Svelte Handbook
  • Swift Handbook

JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list