---
name: templ-htmx
description: Build interactive hypermedia-driven applications with templ and HTMX. Use when creating dynamic UIs, real-time updates, AJAX interactions, mentions 'HTMX', 'dynamic content', or 'interactive templ app'.
---
# Templ + HTMX Integration
## Overview
HTMX enables modern, interactive web applications with minimal JavaScript. Combined with templ's type-safe components, you get fast, reliable hypermedia-driven UIs.
**Key Benefits:**
- No JavaScript framework needed
- Server-side rendering
- Minimal client-side code
- Progressive enhancement
- Type-safe components
## When to Use This Skill
Use when:
- Building interactive UIs
- Creating dynamic content
- User mentions "HTMX", "dynamic updates", "real-time"
- Implementing AJAX-like behavior without JS
- Building SPAs without frameworks
## Quick Start
### 1. Import and Mount HTMX
First, import the htmx package and mount it in your server:
```go
import (
"within.website/x/htmx"
)
func main() {
mux := http.NewServeMux()
// Mount HTMX static files at /.within.website/x/htmx/
htmx.Mount(mux)
// ... other routes
}
```
### 2. Add HTMX to Layout
```templ
package components
import "within.website/x/htmx"
templ Layout(title string) {
{ title }
@htmx.Use()
{ children... }
}
```
The `htmx.Use()` component includes the core HTMX library. You can add extensions:
```templ
// Add SSE and path-params extensions
@htmx.Use("sse", "path-params")
```
Available extensions: `event-header`, `path-params`, `remove-me`, `websocket`.
### 3. Detect HTMX Requests
Use the `htmx.Is()` function to check if a request was made by HTMX:
```go
import "within.website/x/htmx"
func handler(w http.ResponseWriter, r *http.Request) {
if htmx.Is(r) {
// Return partial HTML fragment for HTMX
components.Partial().Render(r.Context(), w)
} else {
// Return full page for direct navigation
components.FullPage().Render(r.Context(), w)
}
}
```
### 4. Create Interactive Component
```templ
templ Counter(count int) {
Count: { strconv.Itoa(count) }
}
```
### 5. Create Handler
```go
func incrementHandler(w http.ResponseWriter, r *http.Request) {
count := getCount() + 1
saveCount(count)
components.Counter(count).Render(r.Context(), w)
}
```
## Core HTMX Attributes
### hx-get / hx-post
Trigger HTTP requests:
```templ
templ SearchBox() {
}
```
Handler:
```go
func searchHandler(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query().Get("q")
results := search(query)
components.SearchResults(results).Render(r.Context(), w)
}
```
### hx-target
Specify where to insert response:
```templ
templ LoadMore(page int) {
}
```
### hx-swap
Control how content is swapped:
```templ
// innerHTML (default)
hx-swap="innerHTML"
// outerHTML - replace element itself
hx-swap="outerHTML"
// beforeend - append inside
hx-swap="beforeend"
// afterend - insert after
hx-swap="afterend"
```
### hx-trigger
Control when requests fire:
```templ
// On click (default for buttons)
// On change