PhoenixDatastar.Actions (PhoenixDatastar v0.1.16)

Copy Markdown View Source

Provides functions for generating Datastar action expressions.

These functions generate Datastar-compatible action strings for use in data-on:* attributes in your templates.

The generated expressions reference $session_id and $event_path Datastar signals, which are automatically initialized by PhoenixDatastar.DefaultHTML (or your custom html_module). This means event/1,2 works in any component without needing to pass session_id or event_path through assigns.

Requirements

  • A <meta name="csrf-token" content="..."> tag must be present in your layout (Phoenix includes this by default)

Summary

Functions

Link component that performs Datastar soft-navigation when possible.

Generates a Datastar @post action expression for triggering server events.

Generates a Datastar @post action expression for in-session soft navigation.

Functions

ds_link(assigns)

Link component that performs Datastar soft-navigation when possible.

Renders an <a> tag with a normal href for accessibility, right-click context menus, and modified clicks (Ctrl/Cmd+click open in new tab). Unmodified left clicks are intercepted for soft navigation via navigate/2.

Attributes

  • :navigate (required) — Target path.
  • :replace (boolean, default false) — Use replaceState instead of pushState.
  • :method (:soft or :hard, default :soft) — Set to :hard to force a full page navigation instead of soft navigation. Useful when navigation requires a full session refresh (e.g., switching workspaces).

Examples

<.ds_link navigate="/dashboard/orgs">Organizations</.ds_link>
<.ds_link navigate="/dashboard/orgs" replace>Organizations</.ds_link>
<.ds_link navigate="/other" method={:hard}>Full Reload</.ds_link>

Attributes

  • navigate (:string) (required)
  • replace (:boolean) - Defaults to false.
  • method (:atom) - Defaults to :soft. Must be one of :soft, or :hard.
  • Global attributes are accepted. Supports all globals plus: ["class", "id", "target", "rel"].

Slots

  • inner_block (required)

event(event_name, opts \\ nil)

@spec event(String.t(), String.t() | nil) :: String.t()

Generates a Datastar @post action expression for triggering server events.

The generated expression references $event_path and $session_id signals, which Datastar resolves client-side. This means it works in any component regardless of nesting depth — no need to pass framework assigns through.

Parameters

  • event_name - The event name to trigger on the server
  • opts - Optional additional options to pass in the request body (as a string)

Examples

# Simple event
<button data-on:click={event("increment")}>+1</button>

# Event with options
<button data-on:click={event("toggle_code", "name: 'counter'")}>Toggle</button>

# With signals
<button data-on:click={event("update", "value: $count")}>Update</button>