ds

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2026 License: MIT Imports: 7 Imported by: 0

README

datastar-templ

Type-safe Datastar attribute helpers for templ templates.
Go Reference Go Report Card CI Status

datastar-templ mascot


datastar-templ is a Go library that provides compile-time type safety for Datastar attributes in templ templates. It bridges the gap between Go's templ templating system and Datastar's hypermedia framework, enabling you to build reactive web applications with full IDE autocomplete and type checking.

Features

  • Type-Safe: Compile-time checks for Datastar attributes with full IDE support
  • High Performance: Optimized with sync.Pool and precise capacity allocation (~200-300ns/op)
  • Complete Coverage: 60+ DOM events, HTTP actions, signals, and modifiers
  • templ Integration: Native templ.Attributes for seamless template usage

Installation

go get github.com/yacobolo/datastar-templ

Tested with Datastar 1.0.0-RC.7. Get started with Datastar.

Usage

Import the package (commonly aliased as ds):

import ds "github.com/yacobolo/datastar-templ"

Quick Start Example

templ TodoApp() {
    <div { ds.Signals(
        ds.JSON("todos", []Todo{}),
        ds.String("newTodo", ""),
        ds.String("filter", ""),
    )... }>
        // Data binding
        <input 
            type="text"
            { ds.Bind("newTodo")... }
            placeholder="New todo"
        />
        
        // Event handlers with modifiers + SSE actions
        <button { ds.OnClick(
            ds.Post("/todos"),
            ds.ModDebounce,
            ds.Ms(300),
        )... }>
            Add Todo
        </button>
        
        // Conditional rendering + merging attributes
        <div { ds.Merge(
            ds.Show("$todos.length > 0"),
            ds.Class(ds.Pair("active", "$filter !== ''")),
        )... }>
            <span { ds.Text("$todos.length + ' items'")... }></span>
        </div>
        
        // Event handlers
        <input 
            type="search"
            { ds.Bind("filter")... }
            { ds.OnInput(
                ds.Get("/search?q=$filter"),
                ds.ModDebounce,
                ds.Ms(300),
            )... }
        />
    </div>
}

Type-Safe Helpers

V2 introduces type-safe helpers that eliminate runtime errors and provide clear API semantics:

Signal Helpers (for data transformation):

ds.Signals(
    ds.Int("count", 0),           // Converts int to string
    ds.String("message", "Hello"), // Adds quotes for JavaScript
    ds.Bool("isOpen", true),       // Formats boolean
    ds.Float("price", 19.99),      // Formats float
    ds.JSON("user", userData),     // Marshals complex types
)

Pair Helper (for expression bindings):

// Use ds.Pair() for all attribute bindings
ds.Class(
    ds.Pair("hidden", "$isHidden"),
    ds.Pair("font-bold", "$isBold"),
)

ds.Computed(
    ds.Pair("total", "$price * $qty"),
)

ds.Attr(
    ds.Pair("disabled", "$loading"),
    ds.Pair("title", "$tooltip"),
)

ds.Style(
    ds.Pair("color", "$textColor"),
    ds.Pair("display", "$visible ? 'block' : 'none'"),
)

// Or use ds.P() shorthand for brevity
ds.Class(ds.P("btn-primary", "$isMain"))

Why two different helpers?

  • Signal helpers (Int, String, etc.) transform Go values into JavaScript-compatible strings
  • Pair helper (Pair or P) simply pairs keys with expressions - no transformation needed

API Overview

See the Go package documentation for the complete API reference including:

  • Signal Helpers: Int(), String(), Bool(), Float(), JSON() for type-safe data transformation
  • Pair Helper: Pair() (or P()) for unified key-value expression bindings
  • 60+ Event Handlers: OnClick, OnInput, OnSubmit, OnKeyDown, etc.
  • HTTP Actions: Get, Post, Put, Patch, Delete with options
  • Signal Management: Signals, Computed, Bind, SignalKey
  • DOM Helpers: Text, Show, Class, Style, Attr
  • Modifiers: Debounce, Throttle, Once, Passive, Capture, etc.
  • Watchers: OnIntersect, OnInterval, OnSignalPatch
  • Utilities: Merge, Ref, Indicator, Init, Effect

Performance

V2 is highly optimized using:

  • sync.Pool for builder reuse across requests
  • Precise capacity allocation to avoid buffer reallocation
  • Direct string building instead of JSON marshaling for primitives

Benchmark results (Apple M2):

BenchmarkSignals/simple-8      203.0 ns/op    392 B/op    5 allocs/op
BenchmarkClass/single-8        143.0 ns/op    376 B/op    4 allocs/op
BenchmarkComputed/single-8     170.2 ns/op    384 B/op    4 allocs/op

The implementation is only ~1.7x slower than raw inline fmt.Sprintf, while providing:

  • ✅ Type safety at compile time
  • ✅ Consistent API across all attributes
  • ✅ Better maintainability
  • ✅ No runtime reflection

Development

Run tests:

go test ./...

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT License - see LICENSE file for details


DatastartemplAPI Reference

Documentation

Overview

Package ds constants. All Datastar attribute names, DOM event names, prefixes, and modifier constants are defined here as the single source of truth.

Unexported constants are used internally by the helper functions. Exported Modifier constants are part of the public API.

Package ds provides type-safe Datastar attribute helpers for templ templates.

Every function returns templ.Attributes, so you can spread directly in templ:

<button { ds.OnClick("$open = true")... }>Open</button>
<div { ds.Show("$visible")... }>Content</div>
<input { ds.Bind("name")... } />

For multiple attributes on one element, use Merge:

<div { ds.Merge(ds.Show("$open"), ds.OnClick("$open = false"))... }>

See https://data-star.dev/reference/attributes

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Attr

func Attr(pairs ...PairItem) templ.Attributes

Attr sets HTML attributes using typed pairs.

{ ds.Attr(ds.Pair("title", "$tooltip"), ds.Pair("disabled", "$loading"))... }

See https://data-star.dev/reference/attributes#data-attr

func AttrKey

func AttrKey(name, expr string, modifiers ...Modifier) templ.Attributes

AttrKey sets a single HTML attribute using keyed syntax.

{ ds.AttrKey("disabled", "$loading")... }
{ ds.AttrKey("title", "'Theme: ' + $theme")... }
Example

Example demonstrates attribute binding

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.AttrKey("disabled", "$isDisabled")
	fmt.Println(attrs["data-attr:disabled"])
}
Output:

$isDisabled

func Bind

func Bind(name string, modifiers ...Modifier) templ.Attributes

Bind creates a two-way data binding between a signal and an element's value.

<input { ds.Bind("name")... } />
<input { ds.Bind("table.search")... } />

See https://data-star.dev/reference/attributes#data-bind

Example

Example demonstrates two-way data binding

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.Bind("email")
	fmt.Println(attrs["data-bind:email"])
}
Output:

true

func BindExpr

func BindExpr(name string) templ.Attributes

BindExpr creates a two-way binding using value syntax.

<input { ds.BindExpr("name")... } />
Example

Example demonstrates value syntax for binding

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.BindExpr("name")
	fmt.Println(attrs["data-bind"])
}
Output:

name

func Class

func Class(pairs ...PairItem) templ.Attributes

Class adds/removes CSS classes using typed pairs.

{ ds.Class(ds.Pair("hidden", "$isHidden"), ds.Pair("font-bold", "$isBold"))... }

See https://data-star.dev/reference/attributes#data-class

Example

Example demonstrates conditional CSS class

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.Class(ds.Pair("active", "$isActive"))
	fmt.Println(attrs["data-class"])
}
Output:

{'active': $isActive}

func ClassKey

func ClassKey(name, expr string, modifiers ...Modifier) templ.Attributes

ClassKey adds/removes a single CSS class using keyed syntax.

{ ds.ClassKey("font-bold", "$isBold")... }
Example

Example demonstrates keyed class syntax

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.ClassKey("active", "$isActive")
	fmt.Println(attrs["data-class:active"])
}
Output:

$isActive

func Computed

func Computed(pairs ...PairItem) templ.Attributes

Computed creates read-only computed signals using typed pairs. Each pair is wrapped in an arrow function.

{ ds.Computed(ds.Pair("total", "$price * $qty"))... }

See https://data-star.dev/reference/attributes#data-computed

Example

Example demonstrates computed signals

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.Computed(ds.Pair("double", "$count * 2"))
	fmt.Println(attrs["data-computed"])
}
Output:

{'double': () => $count * 2}

func ComputedKey

func ComputedKey(name, expr string, modifiers ...Modifier) templ.Attributes

ComputedKey creates a single computed signal using keyed syntax.

{ ds.ComputedKey("total", "$price * $qty")... }
Example

Example demonstrates keyed computed signal

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.ComputedKey("total", "$price * $qty")
	fmt.Println(attrs["data-computed:total"])
}
Output:

$price * $qty

func Delete

func Delete(urlFormat string, args ...any) string

Delete builds a @delete SSE action expression.

ds.Delete("/api/todos/%d", id)
// -> "@delete('/api/todos/42')"
Example

Example demonstrates DELETE action

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	result := ds.Delete("/api/todos/%d", 42)
	fmt.Println(result)
}
Output:

@delete('/api/todos/42')

func Effect

func Effect(expr string) templ.Attributes

Effect executes an expression on load and whenever dependency signals change.

{ ds.Effect("$total = $price * $qty")... }

See https://data-star.dev/reference/attributes#data-effect

Example

Example demonstrates reactive effect

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.Effect("console.log('count changed:', $count)")
	fmt.Println(attrs["data-effect"])
}
Output:

console.log('count changed:', $count)

func Get

func Get(urlFormat string, args ...any) string

Get builds a @get SSE action expression.

ds.Get("/api/updates")
// -> "@get('/api/updates')"

ds.Get("/api/todos/%d", id)
// -> "@get('/api/todos/42')"

ds.Get("/api/updates", ds.Opt("requestCancellation", "disabled"))
// -> "@get('/api/updates',{requestCancellation: 'disabled'})"

ds.Get("/api/todos/%d", id, ds.Opt("openWhenHidden", "true"))
// -> "@get('/api/todos/42',{openWhenHidden: 'true'})"
Example

Example demonstrates GET request action

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	result := ds.Get("/api/data")
	fmt.Println(result)
}
Output:

@get('/api/data')
Example (WithFormatArgs)

Example demonstrates GET request with format arguments

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	result := ds.Get("/api/users/%d", 42)
	fmt.Println(result)
}
Output:

@get('/api/users/42')
Example (WithOptions)

Example demonstrates GET request with options

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	result := ds.Get("/api/data", ds.Opt("retry", "error"), ds.Opt("selector", ".target"))
	fmt.Println(result)
}
Output:

@get('/api/data',{retry: 'error', selector: '.target'})

func Ignore

func Ignore(modifiers ...Modifier) templ.Attributes

Ignore tells Datastar to skip processing an element and its descendants.

{ ds.Ignore()... }
{ ds.Ignore(ds.ModSelf)... }

See https://data-star.dev/reference/attributes#data-ignore

func IgnoreMorph

func IgnoreMorph() templ.Attributes

IgnoreMorph tells PatchElements to skip morphing an element and its children.

{ ds.IgnoreMorph()... }

See https://data-star.dev/reference/attributes#data-ignore-morph

func Indicator

func Indicator(name string, modifiers ...Modifier) templ.Attributes

Indicator creates a boolean signal that is true while a fetch is in flight.

{ ds.Indicator("fetching")... }

See https://data-star.dev/reference/attributes#data-indicator

Example

Example demonstrates loading indicator

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.Indicator("fetching")
	fmt.Println(attrs["data-indicator"])
}
Output:

fetching

func Init

func Init(expr string, modifiers ...Modifier) templ.Attributes

Init runs an expression when the element is loaded into the DOM.

{ ds.Init("$count = 1")... }
{ ds.Init("@get('/updates')", ds.ModDelay, ds.Ms(500))... }

See https://data-star.dev/reference/attributes#data-init

Example

Example demonstrates initialization code

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.Init("setup()")
	fmt.Println(attrs["data-init"])
}
Output:

setup()
Example (WithDelay)

Example demonstrates init with delay

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.Init("load()", ds.ModDelay, ds.Ms(1000))
	fmt.Println(attrs["data-init__delay.1000ms"])
}
Output:

load()

func JSONSignals

func JSONSignals(filter Filter, modifiers ...Modifier) templ.Attributes

JSONSignals sets text content to a JSON-stringified version of signals.

{ ds.JSONSignals(ds.Filter{})... }
{ ds.JSONSignals(ds.Filter{Include: "/user/"}, ds.ModTerse)... }

See https://data-star.dev/reference/attributes#data-json-signals

Example

Example demonstrates JSON signals debug display

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.JSONSignals(ds.Filter{Include: "/user/"})
	fmt.Println(attrs["data-json-signals"])
}
Output:

{include: /user/}

func Merge

func Merge(attrs ...templ.Attributes) templ.Attributes

Merge combines multiple templ.Attributes into one. Use when you need multiple ds attributes on a single element:

<div { ds.Merge(ds.Show("$open"), ds.OnClick("$open = false"))... }>
Example

Example demonstrates merging multiple attributes

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	merged := ds.Merge(
		ds.Show("$visible"),
		ds.OnClick("toggle()"),
		ds.Text("$message"),
	)
	fmt.Printf("Has %d attributes\n", len(merged))
}
Output:

Has 3 attributes

func OnAnimationEnd

func OnAnimationEnd(expr string, modifiers ...Modifier) templ.Attributes

OnAnimationEnd handles the "animationend" event.

func OnAnimationIteration

func OnAnimationIteration(expr string, modifiers ...Modifier) templ.Attributes

OnAnimationIteration handles the "animationiteration" event.

func OnAnimationStart

func OnAnimationStart(expr string, modifiers ...Modifier) templ.Attributes

OnAnimationStart handles the "animationstart" event.

func OnBlur

func OnBlur(expr string, modifiers ...Modifier) templ.Attributes

OnBlur handles the "blur" event.

func OnChange

func OnChange(expr string, modifiers ...Modifier) templ.Attributes

OnChange handles the "change" event.

func OnClick

func OnClick(expr string, modifiers ...Modifier) templ.Attributes

OnClick handles the "click" event.

Example

Example demonstrates basic click handler

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.OnClick("$open = true")
	fmt.Println(attrs["data-on:click"])
}
Output:

$open = true
Example (WithModifiers)

Example demonstrates click handler with debounce modifier

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.OnClick("search()", ds.ModDebounce, ds.Ms(500), ds.Leading)
	fmt.Println(attrs["data-on:click__debounce.500ms.leading"])
}
Output:

search()

func OnContextMenu

func OnContextMenu(expr string, modifiers ...Modifier) templ.Attributes

OnContextMenu handles the "contextmenu" event.

func OnCopy

func OnCopy(expr string, modifiers ...Modifier) templ.Attributes

OnCopy handles the "copy" event.

func OnCut

func OnCut(expr string, modifiers ...Modifier) templ.Attributes

OnCut handles the "cut" event.

func OnDblClick

func OnDblClick(expr string, modifiers ...Modifier) templ.Attributes

OnDblClick handles the "dblclick" event.

func OnDrag

func OnDrag(expr string, modifiers ...Modifier) templ.Attributes

OnDrag handles the "drag" event.

func OnDragEnd

func OnDragEnd(expr string, modifiers ...Modifier) templ.Attributes

OnDragEnd handles the "dragend" event.

func OnDragEnter

func OnDragEnter(expr string, modifiers ...Modifier) templ.Attributes

OnDragEnter handles the "dragenter" event.

func OnDragLeave

func OnDragLeave(expr string, modifiers ...Modifier) templ.Attributes

OnDragLeave handles the "dragleave" event.

func OnDragOver

func OnDragOver(expr string, modifiers ...Modifier) templ.Attributes

OnDragOver handles the "dragover" event.

func OnDragStart

func OnDragStart(expr string, modifiers ...Modifier) templ.Attributes

OnDragStart handles the "dragstart" event.

func OnDrop

func OnDrop(expr string, modifiers ...Modifier) templ.Attributes

OnDrop handles the "drop" event.

func OnError

func OnError(expr string, modifiers ...Modifier) templ.Attributes

OnError handles the "error" event.

func OnEvent

func OnEvent(event, expr string, modifiers ...Modifier) templ.Attributes

OnEvent handles any event by name. Use for custom events or web component events not covered by the typed functions above.

{ ds.OnEvent("table-select", "$table.selected = evt.detail.ids")... }

See https://data-star.dev/reference/attributes#data-on

func OnFocus

func OnFocus(expr string, modifiers ...Modifier) templ.Attributes

OnFocus handles the "focus" event.

func OnFocusIn

func OnFocusIn(expr string, modifiers ...Modifier) templ.Attributes

OnFocusIn handles the "focusin" event.

func OnFocusOut

func OnFocusOut(expr string, modifiers ...Modifier) templ.Attributes

OnFocusOut handles the "focusout" event.

func OnGotPointerCapture

func OnGotPointerCapture(expr string, modifiers ...Modifier) templ.Attributes

OnGotPointerCapture handles the "gotpointercapture" event.

func OnInput

func OnInput(expr string, modifiers ...Modifier) templ.Attributes

OnInput handles the "input" event.

Example

Example demonstrates input event with debounce

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.OnInput("search()", ds.ModDebounce, ds.Ms(300))
	fmt.Println(attrs["data-on:input__debounce.300ms"])
}
Output:

search()

func OnIntersect

func OnIntersect(expr string, modifiers ...Modifier) templ.Attributes

OnIntersect runs an expression when the element intersects with the viewport.

{ ds.OnIntersect("$visible = true", ds.ModOnce, ds.ModFull)... }

See https://data-star.dev/reference/attributes#data-on-intersect

Example

Example demonstrates intersection observer

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.OnIntersect("$visible = true", ds.ModOnce, ds.ModFull)
	fmt.Println(attrs["data-on-intersect__once__full"])
}
Output:

$visible = true
Example (WithThreshold)

Example demonstrates intersection with threshold

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.OnIntersect("$partial = true", ds.ModThreshold, ds.Threshold(0.5))
	fmt.Println(attrs["data-on-intersect__threshold.50"])
}
Output:

$partial = true

func OnInterval

func OnInterval(expr string, modifiers ...Modifier) templ.Attributes

OnInterval runs an expression at a regular interval (default: 1s).

{ ds.OnInterval("$count++", ds.ModDuration, ds.Ms(500))... }

See https://data-star.dev/reference/attributes#data-on-interval

Example

Example demonstrates interval timer

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.OnInterval("tick()", ds.ModDuration, ds.Ms(1000))
	fmt.Println(attrs["data-on-interval__duration.1000ms"])
}
Output:

tick()

func OnInvalid

func OnInvalid(expr string, modifiers ...Modifier) templ.Attributes

OnInvalid handles the "invalid" event.

func OnKeyDown

func OnKeyDown(expr string, modifiers ...Modifier) templ.Attributes

OnKeyDown handles the "keydown" event.

func OnKeyPress

func OnKeyPress(expr string, modifiers ...Modifier) templ.Attributes

OnKeyPress handles the "keypress" event (deprecated but still used).

func OnKeyUp

func OnKeyUp(expr string, modifiers ...Modifier) templ.Attributes

OnKeyUp handles the "keyup" event.

func OnLoad

func OnLoad(expr string, modifiers ...Modifier) templ.Attributes

OnLoad handles the "load" event.

func OnLostPointerCapture

func OnLostPointerCapture(expr string, modifiers ...Modifier) templ.Attributes

OnLostPointerCapture handles the "lostpointercapture" event.

func OnMouseDown

func OnMouseDown(expr string, modifiers ...Modifier) templ.Attributes

OnMouseDown handles the "mousedown" event.

func OnMouseEnter

func OnMouseEnter(expr string, modifiers ...Modifier) templ.Attributes

OnMouseEnter handles the "mouseenter" event.

func OnMouseLeave

func OnMouseLeave(expr string, modifiers ...Modifier) templ.Attributes

OnMouseLeave handles the "mouseleave" event.

func OnMouseMove

func OnMouseMove(expr string, modifiers ...Modifier) templ.Attributes

OnMouseMove handles the "mousemove" event.

func OnMouseOut

func OnMouseOut(expr string, modifiers ...Modifier) templ.Attributes

OnMouseOut handles the "mouseout" event.

func OnMouseOver

func OnMouseOver(expr string, modifiers ...Modifier) templ.Attributes

OnMouseOver handles the "mouseover" event.

func OnMouseUp

func OnMouseUp(expr string, modifiers ...Modifier) templ.Attributes

OnMouseUp handles the "mouseup" event.

func OnPaste

func OnPaste(expr string, modifiers ...Modifier) templ.Attributes

OnPaste handles the "paste" event.

func OnPointerCancel

func OnPointerCancel(expr string, modifiers ...Modifier) templ.Attributes

OnPointerCancel handles the "pointercancel" event.

func OnPointerDown

func OnPointerDown(expr string, modifiers ...Modifier) templ.Attributes

OnPointerDown handles the "pointerdown" event.

func OnPointerEnter

func OnPointerEnter(expr string, modifiers ...Modifier) templ.Attributes

OnPointerEnter handles the "pointerenter" event.

func OnPointerLeave

func OnPointerLeave(expr string, modifiers ...Modifier) templ.Attributes

OnPointerLeave handles the "pointerleave" event.

func OnPointerMove

func OnPointerMove(expr string, modifiers ...Modifier) templ.Attributes

OnPointerMove handles the "pointermove" event.

func OnPointerOut

func OnPointerOut(expr string, modifiers ...Modifier) templ.Attributes

OnPointerOut handles the "pointerout" event.

func OnPointerOver

func OnPointerOver(expr string, modifiers ...Modifier) templ.Attributes

OnPointerOver handles the "pointerover" event.

func OnPointerUp

func OnPointerUp(expr string, modifiers ...Modifier) templ.Attributes

OnPointerUp handles the "pointerup" event.

func OnReset

func OnReset(expr string, modifiers ...Modifier) templ.Attributes

OnReset handles the "reset" event.

func OnScroll

func OnScroll(expr string, modifiers ...Modifier) templ.Attributes

OnScroll handles the "scroll" event.

func OnSelect

func OnSelect(expr string, modifiers ...Modifier) templ.Attributes

OnSelect handles the "select" event.

func OnSignalPatch

func OnSignalPatch(expr string, modifiers ...Modifier) templ.Attributes

OnSignalPatch runs an expression whenever signals are patched.

{ ds.OnSignalPatch("console.log(patch)")... }

See https://data-star.dev/reference/attributes#data-on-signal-patch

Example

Example demonstrates signal patch watcher

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.OnSignalPatch("refresh()")
	fmt.Println(attrs["data-on-signal-patch"])
}
Output:

refresh()

func OnSignalPatchFilter

func OnSignalPatchFilter(filter Filter) templ.Attributes

OnSignalPatchFilter filters which signals trigger data-on-signal-patch.

{ ds.OnSignalPatchFilter(ds.Filter{Include: "/^counter$/"})... }

See https://data-star.dev/reference/attributes#data-on-signal-patch-filter

Example

Example demonstrates filtered signal patch watcher

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.OnSignalPatchFilter(ds.Filter{Include: "/user/", Exclude: "/password/"})
	fmt.Println(attrs["data-on-signal-patch-filter"])
}
Output:

{include: /user/, exclude: /password/}

func OnSubmit

func OnSubmit(expr string, modifiers ...Modifier) templ.Attributes

OnSubmit handles the "submit" event. Datastar automatically prevents default.

Example

Example demonstrates form submission

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.OnSubmit("handleSubmit()", ds.ModPrevent)
	fmt.Println(attrs["data-on:submit__prevent"])
}
Output:

handleSubmit()

func OnTouchCancel

func OnTouchCancel(expr string, modifiers ...Modifier) templ.Attributes

OnTouchCancel handles the "touchcancel" event.

func OnTouchEnd

func OnTouchEnd(expr string, modifiers ...Modifier) templ.Attributes

OnTouchEnd handles the "touchend" event.

func OnTouchMove

func OnTouchMove(expr string, modifiers ...Modifier) templ.Attributes

OnTouchMove handles the "touchmove" event.

func OnTouchStart

func OnTouchStart(expr string, modifiers ...Modifier) templ.Attributes

OnTouchStart handles the "touchstart" event.

func OnTransitionEnd

func OnTransitionEnd(expr string, modifiers ...Modifier) templ.Attributes

OnTransitionEnd handles the "transitionend" event.

func OnWheel

func OnWheel(expr string, modifiers ...Modifier) templ.Attributes

OnWheel handles the "wheel" event.

func Opt

func Opt(key, value string) option

Opt creates an SSE action option with a single-quoted string value.

ds.Opt("requestCancellation", "disabled") // -> requestCancellation: 'disabled'
ds.Opt("contentType", "json")             // -> contentType: 'json'
ds.Opt("retry", "never")                  // -> retry: 'never'

func OptRaw

func OptRaw(key, value string) option

OptRaw creates an SSE action option with a raw (unquoted) value. Use for booleans, numbers, and object/regex values.

ds.OptRaw("openWhenHidden", "true")              // -> openWhenHidden: true
ds.OptRaw("retryMaxCount", "10")                 // -> retryMaxCount: 10
ds.OptRaw("filterSignals", "{include: /^foo/}")  // -> filterSignals: {include: /^foo/}

func Patch

func Patch(urlFormat string, args ...any) string

Patch builds a @patch SSE action expression.

ds.Patch("/api/workcenters/pagesize")
// -> "@patch('/api/workcenters/pagesize')"
Example

Example demonstrates PATCH action

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	result := ds.Patch("/api/users/%d", 5)
	fmt.Println(result)
}
Output:

@patch('/api/users/5')

func Post

func Post(urlFormat string, args ...any) string

Post builds a @post SSE action expression.

ds.Post("/api/workcenters")
// -> "@post('/api/workcenters')"
Example (WithOptions)

Example demonstrates POST request with options

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	result := ds.Post("/api/data", ds.Opt("contentType", "form"))
	fmt.Println(result)
}
Output:

@post('/api/data',{contentType: 'form'})

func PreserveAttr

func PreserveAttr(attrs ...string) templ.Attributes

PreserveAttr preserves attribute values when morphing DOM elements.

{ ds.PreserveAttr("open")... }
{ ds.PreserveAttr("open", "class")... }

See https://data-star.dev/reference/attributes#data-preserve-attr

func Put

func Put(urlFormat string, args ...any) string

Put builds a @put SSE action expression.

ds.Put("/api/todos/%d", id)
// -> "@put('/api/todos/42')"
Example

Example demonstrates PUT action

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	result := ds.Put("/api/users/%d", 10)
	fmt.Println(result)
}
Output:

@put('/api/users/10')

func Ref

func Ref(name string, modifiers ...Modifier) templ.Attributes

Ref creates a signal that is a DOM reference to the element.

{ ds.Ref("myEl")... }

See https://data-star.dev/reference/attributes#data-ref

Example

Example demonstrates element reference

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.Ref("myButton")
	fmt.Println(attrs["data-ref"])
}
Output:

myButton

func Show

func Show(expr string) templ.Attributes

Show shows or hides an element based on a boolean expression.

<div { ds.Show("$visible")... }>Content</div>

See https://data-star.dev/reference/attributes#data-show

Example

Example demonstrates conditional visibility

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.Show("$isOpen")
	fmt.Println(attrs["data-show"])
}
Output:

$isOpen

func SignalKey

func SignalKey(name, expr string, modifiers ...Modifier) templ.Attributes

SignalKey patches a single signal using keyed syntax: data-signals:{name}.

{ ds.SignalKey("foo", "1")... }

See https://data-star.dev/reference/attributes#data-signals

func Signals

func Signals(signals ...Signal) templ.Attributes

Signals patches one or more signals using typed helpers.

{ ds.Signals(ds.Int("count", 0), ds.String("msg", "hello"))... }

See https://data-star.dev/reference/attributes#data-signals

Example

Example demonstrates creating reactive signals

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.Signals(ds.Int("count", 0), ds.String("message", "Hello"))
	fmt.Println(attrs["data-signals"])
}
Output:

{count: 0, message: "Hello"}
Example (Nested)

Example demonstrates nested signal objects using JSON helper

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.Signals(ds.JSON("user", map[string]any{
		"name": "John",
		"age":  30,
	}))
	signal := attrs["data-signals"]
	fmt.Printf("Signal is not empty: %t\n", signal != "")
}
Output:

Signal is not empty: true

func SignalsJSON

func SignalsJSON(jsonStr string, modifiers ...Modifier) templ.Attributes

SignalsJSON patches signals using a pre-built JSON string value. Useful when you've already serialized the signals.

{ ds.SignalsJSON(myJSONString)... }

func Style

func Style(pairs ...PairItem) templ.Attributes

Style sets inline CSS styles using typed pairs.

{ ds.Style(ds.Pair("display", "$hiding && 'none'"), ds.Pair("color", "$textColor"))... }

See https://data-star.dev/reference/attributes#data-style

func StyleKey

func StyleKey(prop, expr string, modifiers ...Modifier) templ.Attributes

StyleKey sets a single inline CSS style using keyed syntax.

{ ds.StyleKey("display", "$hiding && 'none'")... }
Example

Example demonstrates style binding

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.StyleKey("color", "$textColor")
	fmt.Println(attrs["data-style:color"])
}
Output:

$textColor

func Text

func Text(expr string) templ.Attributes

Text binds the text content of an element to an expression.

<span { ds.Text("$count")... }></span>

See https://data-star.dev/reference/attributes#data-text

Example

Example demonstrates text content binding

package main

import (
	"fmt"

	ds "github.com/Yacobolo/datastar-templ"
)

func main() {
	attrs := ds.Text("$count")
	fmt.Println(attrs["data-text"])
}
Output:

$count

Types

type Filter

type Filter struct {
	Include string
	Exclude string
}

Filter is used by attributes that accept include/exclude regex patterns.

type Modifier

type Modifier string

Modifier is a Datastar attribute modifier suffix. Double-underscore modifiers (e.g. __debounce) and dot-tag modifiers (e.g. .leading) are concatenated onto attribute names.

const (
	ModCapture        Modifier = "__capture"
	ModCase           Modifier = "__case"
	ModDebounce       Modifier = "__debounce"
	ModDelay          Modifier = "__delay"
	ModDuration       Modifier = "__duration"
	ModExit           Modifier = "__exit"
	ModFull           Modifier = "__full"
	ModHalf           Modifier = "__half"
	ModIfMissing      Modifier = "__ifmissing"
	ModOnce           Modifier = "__once"
	ModOutside        Modifier = "__outside"
	ModPassive        Modifier = "__passive"
	ModPrevent        Modifier = "__prevent"
	ModSelf           Modifier = "__self"
	ModStop           Modifier = "__stop"
	ModTerse          Modifier = "__terse"
	ModThreshold      Modifier = "__threshold"
	ModThrottle       Modifier = "__throttle"
	ModViewTransition Modifier = "__viewtransition"
	ModWindow         Modifier = "__window"
)

Double-underscore modifiers control event listener behavior and timing.

const (
	Camel      Modifier = ".camel"
	Kebab      Modifier = ".kebab"
	Snake      Modifier = ".snake"
	Pascal     Modifier = ".pascal"
	Leading    Modifier = ".leading"
	NoLeading  Modifier = ".noleading"
	NoTrailing Modifier = ".notrailing"
	Trailing   Modifier = ".trailing"
)

Dot-tag modifiers specify case conversion and timing behavior.

func Duration

func Duration(d time.Duration) Modifier

Duration returns a ".{N}ms" modifier tag, rounded to the nearest millisecond. Panics if the duration is negative.

func Ms

func Ms(n int) Modifier

Ms returns a ".{n}ms" modifier tag. Shorthand for Duration when you have a raw millisecond value.

func Seconds

func Seconds(n int) Modifier

Seconds returns a ".{n}s" modifier tag.

func Threshold

func Threshold(t float64) Modifier

Threshold returns a visibility percentage modifier tag for the __threshold modifier. The value must be between 0.0 (exclusive) and 1.0 (inclusive). Panics if out of range.

type PairItem

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

PairItem represents a key-value expression binding for attributes. Used by Class, Computed, Attr, and Style functions.

func P

func P(key, expr string) PairItem

P is a shorthand alias for Pair. Use this if you prefer more concise template code.

func Pair

func Pair(key, expr string) PairItem

Pair creates a key-value expression binding. This is the recommended helper for all attribute bindings.

ds.Class(ds.Pair("hidden", "$isHidden"))
ds.Computed(ds.Pair("total", "$price * $qty"))
ds.Attr(ds.Pair("disabled", "$loading"))
ds.Style(ds.Pair("color", "$textColor"))

type Signal

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

Signal represents a typed key-value pair for signals.

func Bool

func Bool(key string, value bool) Signal

Bool creates a boolean signal.

func Float

func Float(key string, value float64) Signal

Float creates a float signal.

func Int

func Int(key string, value int) Signal

Int creates an integer signal.

func JSON

func JSON(key string, value any) Signal

JSON creates a signal from any value using JSON marshaling. Use this for complex types like arrays, objects, etc.

func String

func String(key string, value string) Signal

String creates a string signal (properly quoted for JavaScript).

Directories

Path Synopsis
templ: version: v0.3.977
templ: version: v0.3.977

Jump to

Keyboard shortcuts

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