alpine

package
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 27, 2026 License: MIT Imports: 7 Imported by: 4

Documentation

Overview

Package alpine provides Alpine.js integration helpers for ForgeUI.

Alpine.js is a lightweight (~15kb) JavaScript framework that provides reactive and declarative interactivity to server-rendered HTML.

Basic Usage

Use Alpine directive helpers to add interactivity to your templ components:

<div { alpine.XData(map[string]any{"count": 0, "message": "Hello, Alpine!"})... }>
    <button { alpine.XClick("count++")... }>Increment</button>
    <p class="text-xl font-bold" { alpine.XText("'Count: ' + count")... }></p>
</div>

State Management

Use x-data to define component state:

alpine.XData(map[string]any{
    "open": false,
    "items": []any{},
})

Event Handling

Use x-on (or @ shorthand) for event listeners:

alpine.XClick("doSomething()")
alpine.XSubmit("handleSubmit()")
alpine.XKeydown("escape", "close()")

Conditional Rendering

Use x-show for CSS-based visibility or x-if for DOM removal:

alpine.XShow("isVisible")
alpine.XIf("shouldRender")

List Rendering

Use x-for to iterate over arrays:

<template { alpine.XForKeyed("item in items", "item.id")... }>
    <li { alpine.XText("item.name")... }></li>
</template>

Two-Way Binding

Use x-model for form inputs:

<input type="text" { alpine.XModel("name")... }/>

Global Stores

Create global reactive state with Alpine stores:

@alpine.RegisterStores(
    alpine.Store{
        Name: "notifications",
        State: map[string]any{"items": []any{}},
        Methods: `
            add(msg) { this.items.push(msg); },
            clear() { this.items = []; }
        `,
    },
)

Plugins

Load Alpine plugins for additional functionality:

@alpine.Scripts(alpine.PluginFocus, alpine.PluginCollapse, alpine.PluginMask)

Transitions

Add smooth transitions with x-transition:

<div { alpine.XShow("open")... } { alpine.XTransition(myTransition)... }>
    Content
</div>

Routing

Use Pinecone Router for client-side navigation (requires PluginRouter):

<div { alpine.XData(map[string]any{})... }>
    <template { alpine.XRoute("/")... } { alpine.XTemplateInline()... }>
        <h1>Home</h1>
    </template>
</div>

Load router plugin:

@alpine.Scripts(alpine.PluginRouter)

Router provides magic helpers in Alpine expressions:

  • $router: Access to PineconeRouter object
  • $params: Access to route parameters (e.g., $params.id)
  • $history: Navigation history operations

Best Practices

1. Keep component state small and focused 2. Use stores for global state 3. Prefer x-show over x-if when element will toggle frequently 4. Always load plugins BEFORE Alpine core 5. Use XCloak() to prevent flash of unstyled content 6. Be careful with XHtml() to avoid XSS vulnerabilities

Plugin Load Order

CRITICAL: Alpine plugins must be loaded BEFORE Alpine core:

// Correct
@alpine.Scripts(alpine.PluginFocus)

The Scripts() function handles this automatically.

Index

Constants

View Source
const (
	// AlpineCDN is the default CDN URL for Alpine.js
	AlpineCDN = "https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"
)

Variables

This section is empty.

Functions

func CloakCSS

func CloakCSS() templ.Component

CloakCSS returns a templ.Component with CSS to prevent flash of unstyled content.

func Data

func Data(state map[string]any) templ.Attributes

Data is an alias for XData for consistency.

func NavigateTo(path string) string

NavigateTo generates a JavaScript expression for navigating to a path.

func PluginURL

func PluginURL(p Plugin) string

PluginURL returns the CDN URL for the given plugin. Returns empty string if plugin is not recognized.

func RawJS

func RawJS(code string) any

RawJS creates a raw JavaScript value for use in Alpine x-data. This is useful for defining functions and getters in Alpine state.

func RegisterStores

func RegisterStores(stores ...Store) templ.Component

RegisterStores creates a templ.Component that renders a script tag registering Alpine stores. This should be placed before the Alpine.js script tag.

func RouterBack added in v0.0.8

func RouterBack() string

RouterBack generates a JavaScript expression for navigating back in history.

func RouterCanGoBack added in v0.0.8

func RouterCanGoBack() string

RouterCanGoBack generates a JavaScript expression to check if back navigation is possible.

func RouterCanGoForward added in v0.0.8

func RouterCanGoForward() string

RouterCanGoForward generates a JavaScript expression to check if forward navigation is possible.

func RouterForward added in v0.0.8

func RouterForward() string

RouterForward generates a JavaScript expression for navigating forward in history.

func RouterLoading added in v0.0.8

func RouterLoading() string

RouterLoading generates a JavaScript expression to check if the router is loading.

func RouterParam added in v0.0.8

func RouterParam(name string) string

RouterParam generates a JavaScript expression to access a route parameter.

func RouterPath added in v0.0.8

func RouterPath() string

RouterPath generates a JavaScript expression to access the current path.

func RouterSettingsJS added in v1.0.0

func RouterSettingsJS(settings map[string]any) string

RouterSettingsJS generates the inline JavaScript code for configuring Pinecone Router. Use this in a templ script block or with templ.Raw().

func Scripts

func Scripts(plugins ...Plugin) templ.Component

Scripts returns a templ.Component that renders script tags for Alpine.js and any requested plugins.

IMPORTANT: Plugins MUST be loaded BEFORE Alpine.js core. This function ensures correct loading order.

Example (in .templ files):

@alpine.Scripts(alpine.PluginFocus, alpine.PluginCollapse)

func ScriptsImmediate

func ScriptsImmediate(plugins ...Plugin) templ.Component

ScriptsImmediate returns script tags for Alpine.js WITHOUT the defer attribute.

func ScriptsWithNonce

func ScriptsWithNonce(nonce string, plugins ...Plugin) templ.Component

ScriptsWithNonce adds a nonce attribute to script tags for Content Security Policy.

func ScriptsWithVersion

func ScriptsWithVersion(version string, plugins ...Plugin) templ.Component

ScriptsWithVersion returns script tags with a specific Alpine.js version.

func StoreAccess

func StoreAccess(storeName, key string) string

StoreAccess returns the JavaScript expression to access a store property.

func StoreMethod

func StoreMethod(storeName, method, args string) string

StoreMethod returns the JavaScript expression to call a store method.

func XBind

func XBind(attr, expr string) templ.Attributes

XBind creates a dynamic attribute binding using the :attr shorthand.

Example:

alpine.XBind("disabled", "loading")
alpine.XBind("href", "'/users/' + userId")

func XBindClass

func XBindClass(expr string) templ.Attributes

XBindClass creates a :class binding for dynamic classes.

Example:

alpine.XBindClass("{'active': isActive, 'disabled': isDisabled}")
alpine.XBindClass("isActive ? 'text-green-500' : 'text-gray-500'")

func XBindDisabled

func XBindDisabled(expr string) templ.Attributes

XBindDisabled creates a :disabled binding.

func XBindStyle

func XBindStyle(expr string) templ.Attributes

XBindStyle creates a :style binding for dynamic styles.

Example:

alpine.XBindStyle("{'color': textColor, 'fontSize': size + 'px'}")

func XBindValue

func XBindValue(expr string) templ.Attributes

XBindValue creates a :value binding.

func XChange

func XChange(handler string) templ.Attributes

XChange creates an @change event handler.

func XClick

func XClick(handler string) templ.Attributes

XClick creates a @click event handler.

func XClickOnce

func XClickOnce(handler string) templ.Attributes

XClickOnce creates a @click.once event handler that only triggers once.

func XClickOutside

func XClickOutside(handler string) templ.Attributes

XClickOutside creates a @click.outside event handler that triggers when clicking outside the element.

func XClickPrevent

func XClickPrevent(handler string) templ.Attributes

XClickPrevent creates a @click.prevent event handler that prevents the default action.

func XClickStop

func XClickStop(handler string) templ.Attributes

XClickStop creates a @click.stop event handler that stops event propagation.

func XCloak

func XCloak() templ.Attributes

XCloak creates an x-cloak attribute to prevent flash of unstyled content before Alpine initializes. Add CSS: [x-cloak] { display: none !important; }

func XCollapse

func XCollapse() templ.Attributes

XCollapse creates an x-collapse attribute for height transitions. Requires the Collapse plugin to be loaded.

func XData

func XData(state map[string]any) templ.Attributes

XData creates an x-data attribute with the given state. Pass nil or an empty map for an empty x-data scope. Supports RawJS values for embedding raw JavaScript code (functions, getters).

Example:

alpine.XData(map[string]any{
    "open": false,
    "count": 0,
    "increment": alpine.RawJS("function() { this.count++ }"),
})

func XEffect

func XEffect(expr string) templ.Attributes

XEffect creates an x-effect directive that automatically re-runs when any referenced data changes.

func XFor

func XFor(expr string) templ.Attributes

XFor creates an x-for directive for list rendering. Should be used on <template> elements.

Example:

alpine.XFor("item in items")
alpine.XFor("(item, index) in items")

func XForKeyed

func XForKeyed(expr, key string) templ.Attributes

XForKeyed creates an x-for directive with a :key binding for optimized list rendering.

Example (in .templ files):

<template { alpine.XForKeyed("item in items", "item.id")... }>

func XHandler added in v0.0.8

func XHandler(handler string, mods ...HandlerModifier) templ.Attributes

XHandler creates an x-handler attribute for route handler functions.

func XHtml

func XHtml(expr string) templ.Attributes

XHtml creates an x-html directive to set HTML content. WARNING: Be careful with x-html as it can introduce XSS vulnerabilities. Only use with trusted content.

func XId

func XId(items string) templ.Attributes

XId creates an x-id directive for generating unique IDs that are consistent across server/client.

func XIf

func XIf(expr string) templ.Attributes

XIf creates an x-if directive for conditional rendering. Should be used on <template> elements. The element will be added/removed from the DOM based on the expression.

func XIgnore

func XIgnore() templ.Attributes

XIgnore creates an x-ignore attribute to prevent Alpine from initializing this element and its children.

func XInit

func XInit(expr string) templ.Attributes

XInit creates an x-init directive that runs when Alpine initializes.

Example:

alpine.XInit("console.log('initialized')")

func XInitFetch

func XInitFetch(url, target string) templ.Attributes

XInitFetch creates an x-init directive that fetches data from a URL.

Example:

alpine.XInitFetch("/api/users", "users")

func XInput

func XInput(handler string) templ.Attributes

XInput creates an @input event handler.

func XKeydown

func XKeydown(key, handler string) templ.Attributes

XKeydown creates a @keydown event handler with optional key modifier.

Example:

alpine.XKeydown("escape", "close()")
alpine.XKeydown("enter", "submit()")

func XKeyup

func XKeyup(key, handler string) templ.Attributes

XKeyup creates a @keyup event handler with optional key modifier.

func XModel

func XModel(expr string) templ.Attributes

XModel creates an x-model directive for two-way data binding.

Example (in .templ files):

<input type="text" { alpine.XModel("name")... }/>

func XModelDebounce

func XModelDebounce(expr string, ms int) templ.Attributes

XModelDebounce creates an x-model directive with debouncing.

Example:

alpine.XModelDebounce("searchQuery", 300)

func XModelLazy

func XModelLazy(expr string) templ.Attributes

XModelLazy creates an x-model.lazy directive that only updates on the 'change' event instead of 'input'.

func XModelNumber

func XModelNumber(expr string) templ.Attributes

XModelNumber creates an x-model.number directive that automatically converts the value to a number.

func XOn

func XOn(event, handler string) templ.Attributes

XOn creates an event listener using the @event shorthand.

Example:

alpine.XOn("click", "count++")
alpine.XOn("submit", "handleSubmit()")

func XRef

func XRef(name string) templ.Attributes

XRef creates an x-ref attribute to register an element reference. Access via $refs.name in Alpine expressions.

func XRoute added in v0.0.8

func XRoute(path string, opts ...RouteOption) templ.Attributes

XRoute creates an x-route attribute for defining a route path.

func XShow

func XShow(expr string) templ.Attributes

XShow creates an x-show directive for conditional display. The element will be hidden/shown based on the expression.

Example:

alpine.XShow("open")
alpine.XShow("count > 5")

func XStore

func XStore(storeName string) templ.Attributes

XStore creates an x-data directive that initializes with a reference to a store.

func XSubmit

func XSubmit(handler string) templ.Attributes

XSubmit creates a @submit.prevent event handler (prevents default form submission).

func XTeleport

func XTeleport(selector string) templ.Attributes

XTeleport creates an x-teleport directive to move an element to a different part of the DOM.

Example:

alpine.XTeleport("body")
alpine.XTeleport("#modal-container")

func XTemplate added in v0.0.8

func XTemplate(url string, mods ...TemplateModifier) templ.Attributes

XTemplate creates an x-template attribute for loading external templates.

func XTemplateInline added in v0.0.8

func XTemplateInline(mods ...TemplateModifier) templ.Attributes

XTemplateInline creates an x-template attribute with no value, indicating that the template content is defined inline.

func XText

func XText(expr string) templ.Attributes

XText creates an x-text directive to set text content.

Example (in .templ files):

<span { alpine.XText("user.name")... }></span>

func XTransition

func XTransition(t any) templ.Attributes

XTransition applies transition attributes to an element. Accepts both alpine.Transition and animation.Transition.

Example (in .templ files):

<div { alpine.XShow("open")... } { alpine.XTransition(myTransition)... }>

func XTransitionDuration

func XTransitionDuration(ms int) templ.Attributes

XTransitionDuration creates an x-transition with custom duration. Duration should be in milliseconds.

func XTransitionSimple

func XTransitionSimple() templ.Attributes

XTransitionSimple creates a simple x-transition attribute without custom classes. Alpine will use default transition behavior.

Types

type HandlerModifier added in v0.0.8

type HandlerModifier func(*handlerConfig)

HandlerModifier configures handler behavior.

func Global added in v0.0.8

func Global() HandlerModifier

Global marks a handler as global, meaning it will run for every route.

type Plugin

type Plugin string

Plugin represents an official Alpine.js plugin.

const (
	// PluginMask provides input masking functionality
	// https://alpinejs.dev/plugins/mask
	PluginMask Plugin = "mask"

	// PluginIntersect provides intersection observer functionality
	// https://alpinejs.dev/plugins/intersect
	PluginIntersect Plugin = "intersect"

	// PluginPersist provides localStorage persistence
	// https://alpinejs.dev/plugins/persist
	PluginPersist Plugin = "persist"

	// PluginFocus provides focus management utilities
	// https://alpinejs.dev/plugins/focus
	PluginFocus Plugin = "focus"

	// PluginCollapse provides smooth height transitions
	// https://alpinejs.dev/plugins/collapse
	PluginCollapse Plugin = "collapse"

	// PluginAnchor provides element positioning
	// https://alpinejs.dev/plugins/anchor
	PluginAnchor Plugin = "anchor"

	// PluginMorph provides DOM morphing capabilities
	// https://alpinejs.dev/plugins/morph
	PluginMorph Plugin = "morph"

	// PluginSort provides drag-and-drop sorting
	// https://alpinejs.dev/plugins/sort
	PluginSort Plugin = "sort"

	// PluginRouter provides client-side routing for Alpine.js
	// https://github.com/pinecone-router/router
	PluginRouter Plugin = "router"
)

func AllPlugins

func AllPlugins() []Plugin

AllPlugins returns a list of all available plugins.

type RouteOption added in v0.0.8

type RouteOption func(*routeConfig)

RouteOption configures route behavior.

func WithRouteName added in v0.0.8

func WithRouteName(name string) RouteOption

WithRouteName sets a name for the route.

type Store

type Store struct {
	// Name is the store identifier (accessed via $store.name)
	Name string

	// State is the initial state as a map
	State map[string]any

	// Methods is raw JavaScript code defining store methods
	// Will be merged with the state object
	Methods string
}

Store represents an Alpine.js global store definition.

type TemplateModifier added in v0.0.8

type TemplateModifier func(*templateConfig)

TemplateModifier configures template behavior.

func Interpolate added in v0.0.8

func Interpolate() TemplateModifier

Interpolate enables named route params in template URLs.

func Preload added in v0.0.8

func Preload() TemplateModifier

Preload causes the template to be fetched after page load at low priority.

func TargetID added in v0.0.8

func TargetID(id string) TemplateModifier

TargetID specifies an element ID where the template should be rendered.

type Transition

type Transition struct {
	// Enter classes applied during entire enter transition
	Enter string

	// EnterStart classes applied before enter, removed one frame after
	EnterStart string

	// EnterEnd classes applied one frame after enter starts, removed when transition ends
	EnterEnd string

	// Leave classes applied during entire leave transition
	Leave string

	// LeaveStart classes applied before leave, removed one frame after
	LeaveStart string

	// LeaveEnd classes applied one frame after leave starts, removed when transition ends
	LeaveEnd string
}

Transition represents Alpine.js transition configuration. Used with x-transition or x-show for smooth animations.

func (*Transition) Attrs

func (t *Transition) Attrs() templ.Attributes

Attrs converts the transition to Alpine.js x-transition attributes.

type TransitionBuilder

type TransitionBuilder struct {
	// contains filtered or unexported fields
}

TransitionBuilder provides a fluent API for building transitions.

func NewTransition

func NewTransition() *TransitionBuilder

NewTransition creates a new transition builder.

func (*TransitionBuilder) Build

func (b *TransitionBuilder) Build() *Transition

Build returns the completed transition.

func (*TransitionBuilder) Enter

func (b *TransitionBuilder) Enter(classes string) *TransitionBuilder

Enter sets the enter transition classes.

func (*TransitionBuilder) EnterEnd

func (b *TransitionBuilder) EnterEnd(classes string) *TransitionBuilder

EnterEnd sets the enter end classes.

func (*TransitionBuilder) EnterStart

func (b *TransitionBuilder) EnterStart(classes string) *TransitionBuilder

EnterStart sets the enter start classes.

func (*TransitionBuilder) Leave

func (b *TransitionBuilder) Leave(classes string) *TransitionBuilder

Leave sets the leave transition classes.

func (*TransitionBuilder) LeaveEnd

func (b *TransitionBuilder) LeaveEnd(classes string) *TransitionBuilder

LeaveEnd sets the leave end classes.

func (*TransitionBuilder) LeaveStart

func (b *TransitionBuilder) LeaveStart(classes string) *TransitionBuilder

LeaveStart sets the leave start classes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL