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
- func CloakCSS() g.Node
- func Data(state map[string]any) g.Node
- func PluginURL(p Plugin) string
- func RawJS(code string) any
- func RegisterStores(stores ...Store) g.Node
- func Scripts(plugins ...Plugin) g.Node
- func ScriptsImmediate(plugins ...Plugin) g.Node
- func ScriptsWithNonce(nonce string, plugins ...Plugin) g.Node
- func ScriptsWithVersion(version string, plugins ...Plugin) g.Node
- func StoreAccess(storeName, key string) string
- func StoreMethod(storeName, method, args string) string
- func XBind(attr, expr string) g.Node
- func XBindClass(expr string) g.Node
- func XBindDisabled(expr string) g.Node
- func XBindStyle(expr string) g.Node
- func XBindValue(expr string) g.Node
- func XChange(handler string) g.Node
- func XClick(handler string) g.Node
- func XClickOnce(handler string) g.Node
- func XClickOutside(handler string) g.Node
- func XClickPrevent(handler string) g.Node
- func XClickStop(handler string) g.Node
- func XCloak() g.Node
- func XCollapse() g.Node
- func XData(state map[string]any) g.Node
- func XEffect(expr string) g.Node
- func XFor(expr string) g.Node
- func XForKeyed(expr, key string) []g.Node
- func XHtml(expr string) g.Node
- func XId(items string) g.Node
- func XIf(expr string) g.Node
- func XIgnore() g.Node
- func XInit(expr string) g.Node
- func XInitFetch(url, target string) g.Node
- func XInput(handler string) g.Node
- func XKeydown(key, handler string) g.Node
- func XKeyup(key, handler string) g.Node
- func XModel(expr string) g.Node
- func XModelDebounce(expr string, ms int) g.Node
- func XModelLazy(expr string) g.Node
- func XModelNumber(expr string) g.Node
- func XOn(event, handler string) g.Node
- func XRef(name string) g.Node
- func XShow(expr string) g.Node
- func XStore(storeName string) g.Node
- func XSubmit(handler string) g.Node
- func XTeleport(selector string) g.Node
- func XText(expr string) g.Node
- func XTransition(t any) []g.Node
- func XTransitionDuration(ms int) g.Node
- func XTransitionSimple() g.Node
- type Plugin
- type Store
- type Transition
- type TransitionBuilder
- func (b *TransitionBuilder) Build() *Transition
- func (b *TransitionBuilder) Enter(classes string) *TransitionBuilder
- func (b *TransitionBuilder) EnterEnd(classes string) *TransitionBuilder
- func (b *TransitionBuilder) EnterStart(classes string) *TransitionBuilder
- func (b *TransitionBuilder) Leave(classes string) *TransitionBuilder
- func (b *TransitionBuilder) LeaveEnd(classes string) *TransitionBuilder
- func (b *TransitionBuilder) LeaveStart(classes string) *TransitionBuilder
Constants ¶
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 ¶
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 PluginURL ¶
PluginURL returns the CDN URL for the given plugin. Returns empty string if plugin is not recognized.
func RawJS ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
StoreAccess returns the JavaScript expression to access a store property.
Example:
alpine.StoreAccess("cart", "items") // Returns: "$store.cart.items"
func StoreMethod ¶
StoreMethod returns the JavaScript expression to call a store method.
Example:
alpine.StoreMethod("cart", "addItem", "product") // Returns: "$store.cart.addItem(product)"
func XBind ¶
XBind creates a dynamic attribute binding using the :attr shorthand.
Example:
alpine.XBind("disabled", "loading")
alpine.XBind("href", "'/users/' + userId")
func XBindClass ¶
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 ¶
XBindDisabled creates a :disabled binding.
func XBindStyle ¶
XBindStyle creates a :style binding for dynamic styles.
Example:
alpine.XBindStyle("{'color': textColor, 'fontSize': size + 'px'}")
func XClickOnce ¶
XClickOnce creates a @click.once event handler that only triggers once.
func XClickOutside ¶
XClickOutside creates a @click.outside event handler that triggers when clicking outside the element.
func XClickPrevent ¶
XClickPrevent creates a @click.prevent event handler that prevents the default action.
func XClickStop ¶
XClickStop creates a @click.stop event handler that stops event propagation.
func XCloak ¶
XCloak creates an x-cloak attribute to prevent flash of unstyled content before Alpine initializes. Add CSS: [x-cloak] { display: none !important; }
func XCollapse ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
XId creates an x-id directive for generating unique IDs that are consistent across server/client.
Example:
alpine.XId("['input']")
func XIf ¶
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 ¶
XIgnore creates an x-ignore attribute to prevent Alpine from initializing this element and its children.
func XInit ¶
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 ¶
XInitFetch creates an x-init directive that fetches data from a URL.
Example:
alpine.XInitFetch("/api/users", "users")
func XKeydown ¶
XKeydown creates a @keydown event handler with optional key modifier.
Example:
alpine.XKeydown("escape", "close()")
alpine.XKeydown("enter", "submit()")
func XModel ¶
XModel creates an x-model directive for two-way data binding.
Example:
html.Input(
html.Type("text"),
alpine.XModel("name"),
)
func XModelDebounce ¶
XModelDebounce creates an x-model directive with debouncing.
Example:
alpine.XModelDebounce("searchQuery", 300)
func XModelLazy ¶
XModelLazy creates an x-model.lazy directive that only updates on the 'change' event instead of 'input'.
func XModelNumber ¶
XModelNumber creates an x-model.number directive that automatically converts the value to a number.
func XOn ¶
XOn creates an event listener using the @event shorthand.
Example:
alpine.XOn("click", "count++")
alpine.XOn("submit", "handleSubmit()")
func XRef ¶
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 ¶
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 ¶
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 XTeleport ¶
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 ¶
XText creates an x-text directive to set text content.
Example:
html.Span(alpine.XText("user.name"))
func XTransition ¶
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 ¶
XTransitionDuration creates an x-transition with custom duration. Duration should be in milliseconds.
Example:
alpine.XTransitionDuration(300) // 300ms transition
func XTransitionSimple ¶
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" )
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.