alpine

package
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2026 License: MIT Imports: 7 Imported by: 0

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 components:

html.Div(
    alpine.XData(map[string]any{
        "count": 0,
        "message": "Hello, Alpine!",
    }),
    html.Button(
        alpine.XClick("count++"),
        g.Text("Increment"),
    ),
    html.P(
        html.Class("text-xl font-bold"),
        alpine.XText("'Count: ' + count"),
    ),
)

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:

html.Template(
    g.Group(alpine.XForKeyed("item in items", "item.id")),
    html.Li(alpine.XText("item.name")),
)

Two-Way Binding

Use x-model for form inputs:

html.Input(
    html.Type("text"),
    alpine.XModel("name"),
)

Global Stores

Create global reactive state with Alpine stores:

alpine.RegisterStores(
    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,    // Focus management
    alpine.PluginCollapse, // Height transitions
    alpine.PluginMask,     // Input masking
)

Transitions

Add smooth transitions with x-transition:

html.Div(
    alpine.XShow("open"),
    g.Group(alpine.XTransition(animation.FadeIn())),
    g.Text("Content"),
)

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) // Loads plugin, then Alpine

// Wrong - will not work
// Load Alpine first, then try to add plugin

The Scripts() function handles this automatically.

Index

Constants

View Source
const (
	// AlpineCDN is the default CDN URL for Alpine.js
	// Using 3.x.x for automatic minor/patch updates
	AlpineCDN = "https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"
)

Variables

This section is empty.

Functions

func CloakCSS

func CloakCSS() g.Node

CloakCSS returns a style tag with CSS to prevent flash of unstyled content. Add this to your <head> section when using x-cloak.

Example:

html.Head(
    alpine.CloakCSS(),
    // ... other head elements
)

func Data

func Data(state map[string]any) g.Node

Data is an alias for XData for consistency.

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) g.Node

RegisterStores creates a script tag that registers Alpine stores. This should be placed before the Alpine.js script tag.

Example:

alpine.RegisterStores(
    Store{
        Name: "cart",
        State: map[string]any{"items": []any{}, "total": 0},
        Methods: `
            addItem(item) { this.items.push(item); },
            clear() { this.items = []; this.total = 0; }
        `,
    },
)

func Scripts

func Scripts(plugins ...Plugin) g.Node

Scripts returns 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:

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

Generates:

<script defer src="...focus@3.x.x..."></script>
<script defer src="...collapse@3.x.x..."></script>
<script defer src="...alpinejs@3.x.x..."></script>

func ScriptsImmediate

func ScriptsImmediate(plugins ...Plugin) g.Node

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

Use this when placing scripts at the END of the <body> tag with inline store registrations. The scripts will execute immediately in document order.

IMPORTANT: Only use this when Alpine stores are registered inline in the body. If stores are not needed or scripts are in <head>, use Scripts() instead.

Example:

html.Body(
    toast.RegisterToastStore(),  // Inline store registration
    // ... content
    alpine.ScriptsImmediate(alpine.PluginFocus),  // Execute immediately
)

func ScriptsWithNonce

func ScriptsWithNonce(nonce string, plugins ...Plugin) g.Node

ScriptsWithNonce adds a nonce attribute to script tags for Content Security Policy. Use this when you have CSP enabled.

Example:

alpine.ScriptsWithNonce("random-nonce-value", alpine.PluginFocus)

func ScriptsWithVersion

func ScriptsWithVersion(version string, plugins ...Plugin) g.Node

ScriptsWithVersion returns script tags with a specific Alpine.js version. Useful for pinning to a specific version in production.

Example:

alpine.ScriptsWithVersion("3.13.3", alpine.PluginFocus)

func StoreAccess

func StoreAccess(storeName, key string) string

StoreAccess returns the JavaScript expression to access a store property.

Example:

alpine.StoreAccess("cart", "items") // Returns: "$store.cart.items"

func StoreMethod

func StoreMethod(storeName, method, args string) string

StoreMethod returns the JavaScript expression to call a store method.

Example:

alpine.StoreMethod("cart", "addItem", "product") // Returns: "$store.cart.addItem(product)"

func XBind

func XBind(attr, expr string) g.Node

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) g.Node

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) g.Node

XBindDisabled creates a :disabled binding.

func XBindStyle

func XBindStyle(expr string) g.Node

XBindStyle creates a :style binding for dynamic styles.

Example:

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

func XBindValue

func XBindValue(expr string) g.Node

XBindValue creates a :value binding.

func XChange

func XChange(handler string) g.Node

XChange creates an @change event handler.

func XClick

func XClick(handler string) g.Node

XClick creates a @click event handler.

func XClickOnce

func XClickOnce(handler string) g.Node

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

func XClickOutside

func XClickOutside(handler string) g.Node

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

func XClickPrevent

func XClickPrevent(handler string) g.Node

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

func XClickStop

func XClickStop(handler string) g.Node

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

func XCloak

func XCloak() g.Node

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() g.Node

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

Example:

html.Div(
    alpine.XShow("expanded"),
    alpine.XCollapse(),
    g.Text("Collapsible content"),
)

func XData

func XData(state map[string]any) g.Node

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) g.Node

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

Example:

alpine.XEffect("console.log('count is now', count)")

func XFor

func XFor(expr string) g.Node

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) []g.Node

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

Example:

html.Template(
    g.Group(alpine.XForKeyed("item in items", "item.id")),
    html.Div(alpine.XText("item.name")),
)

func XHtml

func XHtml(expr string) g.Node

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.

Example:

html.Div(alpine.XHtml("sanitizedContent"))

func XId

func XId(items string) g.Node

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

Example:

alpine.XId("['input']")

func XIf

func XIf(expr string) g.Node

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.

Example:

html.Template(
    alpine.XIf("isVisible"),
    html.Div(g.Text("Content")),
)

func XIgnore

func XIgnore() g.Node

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

func XInit

func XInit(expr string) g.Node

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

Example:

alpine.XInit("console.log('initialized')")
alpine.XInit("fetch('/api/data').then(r => r.json()).then(d => items = d)")

func XInitFetch

func XInitFetch(url, target string) g.Node

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

Example:

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

func XInput

func XInput(handler string) g.Node

XInput creates an @input event handler.

func XKeydown

func XKeydown(key, handler string) g.Node

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) g.Node

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

func XModel

func XModel(expr string) g.Node

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

Example:

html.Input(
    html.Type("text"),
    alpine.XModel("name"),
)

func XModelDebounce

func XModelDebounce(expr string, ms int) g.Node

XModelDebounce creates an x-model directive with debouncing.

Example:

alpine.XModelDebounce("searchQuery", 300)

func XModelLazy

func XModelLazy(expr string) g.Node

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

func XModelNumber

func XModelNumber(expr string) g.Node

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

func XOn

func XOn(event, handler string) g.Node

XOn creates an event listener using the @event shorthand.

Example:

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

func XRef

func XRef(name string) g.Node

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

Example:

html.Input(alpine.XRef("emailInput"))
html.Button(alpine.XClick("$refs.emailInput.focus()"))

func XShow

func XShow(expr string) g.Node

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) g.Node

XStore creates an x-data directive that initializes with a reference to a store. This allows components to reactively use store data.

Example:

alpine.XStore("cart") // x-data="$store.cart"

func XSubmit

func XSubmit(handler string) g.Node

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

func XTeleport

func XTeleport(selector string) g.Node

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 XText

func XText(expr string) g.Node

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

Example:

html.Span(alpine.XText("user.name"))

func XTransition

func XTransition(t any) []g.Node

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

Example:

html.Div(
    alpine.XShow("open"),
    g.Group(alpine.XTransition(myTransition)),
    g.Text("Content"),
)

func XTransitionDuration

func XTransitionDuration(ms int) g.Node

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

Example:

alpine.XTransitionDuration(300) // 300ms transition

func XTransitionSimple

func XTransitionSimple() g.Node

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

Types

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"
)

func AllPlugins

func AllPlugins() []Plugin

AllPlugins returns a list of all available plugins.

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.

Example:

Store{
    Name: "notifications",
    State: map[string]any{
        "items": []any{},
        "count": 0,
    },
    Methods: `
        add(item) {
            this.items.push(item);
            this.count++;
        },
        clear() {
            this.items = [];
            this.count = 0;
        }
    `,
}

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() []g.Node

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