templ

package
v0.1.13 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2026 License: Apache-2.0 Imports: 13 Imported by: 1

Documentation

Overview

Package templ provides Templ integration helpers for GoSPA reactive bindings.

Package templ provides component helpers for GoSPA.

Package templ provides event handler helpers for GoSPA.

Package templ provides island rendering helpers for GoSPA templates.

Package templ provides layout helpers for GoSPA.

Package templ provides PPR (Partial Prerendering) helpers for GoSPA.

PPR splits a page into a static shell (cached at first render) and named dynamic slots that are re-rendered fresh on every request. The shell is streamed first with slot placeholders (<!--gospa-slot:name-->), then each dynamic slot fragment is appended inline.

Package templ provides rendering utilities for GoSPA.

Package templ provides streaming SSR support for GoSPA.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Alt

func Alt(alt string) templ.Attributes

Alt generates an alt attribute.

func Aria

func Aria(name string, value any) templ.Attributes

Aria generates an aria-* attribute.

func AttrBinding

func AttrBinding(attr string, key string) templ.Attributes

AttrBinding creates an attribute binding. Usage: <a { templ.AttrBinding("href", "url") }></a>

func AttrBindings

func AttrBindings(attrs map[string]string) templ.Attributes

AttrBindings creates multiple attribute bindings. Usage: <a { templ.AttrBindings(map[string]string{"href": "url", "title": "tooltip"}) }></a>

func Attrs

func Attrs(attrs ...templ.Attributes) templ.Attributes

Attrs renders multiple attributes.

func Bind

func Bind(key string, bindType BindingType) templ.Attributes

Bind creates a data-bind attribute for reactive bindings. Usage: <div { templ.Bind("count", templ.TextBind) }>{ count }</div>

func BindWithAttr

func BindWithAttr(key string, attr string, bindType BindingType) templ.Attributes

BindWithAttr creates a data-bind attribute for attribute-specific bindings. Usage: <input { templ.BindWithAttr("value", "placeholder", templ.AttrBind) } />

func BindWithTransform

func BindWithTransform(key string, bindType BindingType, transform string) templ.Attributes

BindWithTransform creates a data-bind attribute with a transform function. Usage: <span { templ.BindWithTransform("price", templ.TextBind, "formatCurrency") }></span>

func CSS

func CSS(href string) templ.Component

CSS returns a link tag for a stylesheet.

func CSSInline

func CSSInline(css string) templ.Component

CSSInline returns an inline style tag.

func Capture

func Capture() templ.Attributes

Capture creates a capture event listener modifier. Usage: <div { templ.Capture() } onclick="handleCapture">Capture</div>

func Checked

func Checked(key string) templ.Attributes

Checked creates a checked binding for checkboxes. Usage: <input type="checkbox" { templ.Checked("agree") } />

func CheckedAttr

func CheckedAttr(checked bool) templ.Attributes

CheckedAttr generates a checked attribute.

func Class

func Class(classes ...string) templ.Attributes

Class generates a class attribute from multiple class names.

func ClassBinding

func ClassBinding(key string, className string) templ.Attributes

ClassBinding creates a class binding that toggles based on state. Usage: <div { templ.ClassBinding("isActive", "active") }></div>

func ClassBindings

func ClassBindings(classes map[string]string) templ.Attributes

ClassBindings creates multiple class bindings. Usage: <div { templ.ClassBindings(map[string]string{"active": "isActive", "disabled": "isDisabled"}) }></div>

func ClassIf

func ClassIf(classes map[string]bool) templ.Attributes

ClassIf generates a class attribute with conditional classes.

func ClientOnly

func ClientOnly(name string, placeholder ...templ.Component) templ.Component

ClientOnly renders content only on the client.

func DataAttrs

func DataAttrs(data map[string]any) templ.Attributes

DataAttrs generates data attributes from a map.

func Debounced

func Debounced(event string, handler string, ms int) templ.Attributes

Debounced creates a debounced event handler. Usage: <input { templ.Debounced("input", "search", 300) } />

func Decrement

func Decrement(key string, amount int) templ.Attributes

Decrement creates a decrement handler for numeric state. Usage: <button { templ.Decrement("count", 1) }>-</button>

func Deferred

func Deferred(name string, placeholder templ.Component, loader func() (templ.Component, error)) templ.Component

Deferred renders a deferred island with a placeholder.

func Disabled

func Disabled(disabled bool) templ.Attributes

Disabled generates a disabled attribute.

func DynamicSlot added in v0.1.4

func DynamicSlot(name string, content templ.Component) templ.Component

DynamicSlot creates a templ.Component that behaves differently depending on the rendering pass:

  • Shell build (IsPPRShellBuild == true): emits <!--gospa-slot:name--> placeholder.
  • Normal request: wraps content in <div data-gospa-slot="name">…</div>.

Use this inside page templ components registered with StrategyPPR. The slot name must match a key in RouteOptions.DynamicSlots and a SlotFunc registered with routing.RegisterSlot for the same page path.

func Empty

func Empty() templ.Component

Empty renders nothing.

func ErrorBoundary

func ErrorBoundary(content templ.Component, fallback func(error) templ.Component) templ.Component

ErrorBoundary catches rendering errors from content and renders a fallback UI instead

func EventModifiers

func EventModifiers(modifiers ...string) templ.Attributes

EventModifiers combines multiple event modifiers. Usage: <button { templ.EventModifiers("prevent", "stop") }>Click</button>

func Favicon

func Favicon(href string) templ.Component

Favicon returns a link tag for a favicon.

func For

func For[T any](items []T, render func(T, int) templ.Component) templ.Component

For renders a list of items.

func ForKey

func ForKey[T any, K comparable](items []T, keyFn func(T) K, render func(T, int) templ.Component) templ.Component

ForKey renders a list of items with keys.

func FormAction

func FormAction(action string) templ.Attributes

FormAction creates a form action handler. Usage: <button type="submit" { templ.FormAction("createUser") }>Create</button>

func Fragment

func Fragment(components ...templ.Component) templ.Component

Fragment renders a fragment of components.

func GetLayoutData

func GetLayoutData(ctx context.Context) map[string]any

GetLayoutData gets layout data from context.

func GetLayoutParam

func GetLayoutParam(ctx context.Context, key string) string

GetLayoutParam gets a route parameter from layout context.

func GetLayoutPath

func GetLayoutPath(ctx context.Context) string

GetLayoutPath gets the current path from layout context.

func HTML

func HTML(key string) templ.Attributes

HTML creates an HTML content binding. Usage: <div { templ.HTML("content") }></div>

func HTMLContent

func HTMLContent(html string) templ.Component

HTMLContent renders HTML content safely (already escaped).

func HTMLPage

func HTMLPage(lang string, head, body templ.Component) templ.Component

HTMLPage returns a complete HTML page.

func Head(components ...templ.Component) templ.Component

Head returns a component that renders content in the head.

func HeadLink(rel, href string, extraAttrs ...map[string]string) templ.Component

HeadLink creates a link tag with data-gospa-head attribute.

func HeadMeta

func HeadMeta(name, content string) templ.Component

HeadMeta creates a meta tag with data-gospa-head attribute.

func HeadMetaProp

func HeadMetaProp(property, content string) templ.Component

HeadMetaProp creates a meta property tag with data-gospa-head attribute.

func HeadScript

func HeadScript(src string, async, defer_ bool) templ.Component

HeadScript creates a script tag with data-gospa-head attribute.

func HeadStyle

func HeadStyle(href string) templ.Component

HeadStyle creates a stylesheet link with data-gospa-head attribute.

func HeadTitle

func HeadTitle(title string) templ.Component

HeadTitle creates a title tag with data-gospa-head attribute.

func Hidden

func Hidden(hidden bool) templ.Attributes

Hidden generates a hidden attribute.

func HighPriorityIsland

func HighPriorityIsland(name string, content templ.Component) templ.Component

HighPriorityIsland creates a high-priority island.

func Href

func Href(href string) templ.Attributes

Href generates an href attribute.

func ID

func ID(id string) templ.Attributes

ID generates an id attribute.

func IdleIsland

func IdleIsland(name string, content templ.Component, maxDelay ...int) templ.Component

IdleIsland creates an island that hydrates during idle time.

func IfBinding

func IfBinding(key string) templ.Attributes

IfBinding creates a conditional rendering binding. Usage: <div { templ.IfBinding("shouldRender") }></div>

func Increment

func Increment(key string, amount int) templ.Attributes

Increment creates an increment handler for numeric state. Usage: <button { templ.Increment("count", 1) }>+</button>

func InjectState

func InjectState(ctx context.Context, key string) (any, bool)

InjectState injects state from parent components.

func InteractionIsland

func InteractionIsland(name string, content templ.Component) templ.Component

InteractionIsland creates an island that hydrates on first interaction.

func IsPPRShellBuild added in v0.1.4

func IsPPRShellBuild(ctx context.Context) bool

IsPPRShellBuild reports whether ctx is in a PPR shell-build pass.

func Island

func Island(name string, content templ.Component, opts ...IslandOptions) templ.Component

Island creates an island component with the given name and content.

func IslandDataScript

func IslandDataScript() templ.Component

IslandDataScript generates a script with serialized island data.

func IslandScript

func IslandScript() templ.Component

IslandScript generates the script tag for island hydration.

func IslandWithProps

func IslandWithProps(name string, props map[string]any, content templ.Component, opts ...IslandOptions) templ.Component

IslandWithProps creates an island with props.

func LazyIsland

func LazyIsland(name string, content templ.Component, threshold ...int) templ.Component

LazyIsland creates a lazily hydrated island.

func ListBinding

func ListBinding(key string, itemName string) templ.Attributes

ListBinding creates a list rendering binding. Usage: <ul { templ.ListBinding("items", "item") }><li>{ item }</li></ul>

func ListBindingWithKey

func ListBindingWithKey(key string, itemName string, keyField string) templ.Attributes

ListBindingWithKey creates a list rendering binding with a key field. Usage: <ul { templ.ListBindingWithKey("items", "item", "id") }><li>{ item.name }</li></ul>

func LowPriorityIsland

func LowPriorityIsland(name string, content templ.Component) templ.Component

LowPriorityIsland creates a low-priority island.

func MergeProps

func MergeProps(props ...map[string]any) map[string]any

MergeProps merges multiple props maps.

func Meta

func Meta(name, content string) templ.Component

Meta returns a meta tag.

func MetaProperty

func MetaProperty(property, content string) templ.Component

MetaProperty returns a meta property tag (for Open Graph, etc.).

func Name

func Name(name string) templ.Attributes

Name generates a name attribute.

func Navigate(path string) templ.Attributes

Navigate creates a client-side navigation handler. Usage: <button { templ.Navigate("/about") }>Go to About</button>

func NavigateBack() templ.Attributes

NavigateBack creates a back navigation handler. Usage: <button { templ.NavigateBack() }>Go Back</button>

func On

func On(event string, handler string) templ.Attributes

On creates an event handler attribute. Usage: <button { templ.On("click", "increment") }>Click me</button>

func OnAltKey

func OnAltKey(key string, handler string) templ.Attributes

OnAltKey creates a handler for Alt + key combination. Usage: <input { templ.OnAltKey("n", "newItem") } />

func OnBlur

func OnBlur(handler string) templ.Attributes

OnBlur creates a blur handler. Usage: <input { templ.OnBlur("handleBlur") } />

func OnChange

func OnChange(handler string) templ.Attributes

OnChange creates a change handler. Usage: <select { templ.OnChange("handleChange") }></select>

func OnClick

func OnClick(handler string) templ.Attributes

OnClick creates a click handler. Usage: <button { templ.OnClick("handleClick") }>Click</button>

func OnClickPrevent

func OnClickPrevent(handler string) templ.Attributes

OnClickPrevent creates a click handler with preventDefault. Usage: <a href="/link" { templ.OnClickPrevent("handleClick") }>Click</a>

func OnCtrlKey

func OnCtrlKey(key string, handler string) templ.Attributes

OnCtrlKey creates a handler for Ctrl/Cmd + key combination. Usage: <input { templ.OnCtrlKey("s", "save") } />

func OnFocus

func OnFocus(handler string) templ.Attributes

OnFocus creates a focus handler. Usage: <input { templ.OnFocus("handleFocus") } />

func OnInput

func OnInput(handler string) templ.Attributes

OnInput creates an input handler. Usage: <input { templ.OnInput("handleInput") } />

func OnKey

func OnKey(key string, handler string) templ.Attributes

OnKey creates a keyboard event handler for specific keys. Usage: <input { templ.OnKey("Enter", "submit") } />

func OnKeyCombo

func OnKeyCombo(combo string, handler string) templ.Attributes

OnKeyCombo creates a handler for key combinations. Usage: <input { templ.OnKeyCombo("ctrl+shift+s", "saveAll") } />

func OnKeydown

func OnKeydown(handler string) templ.Attributes

OnKeydown creates a keydown handler. Usage: <input { templ.OnKeydown("handleKeydown") } />

func OnKeys

func OnKeys(handlers map[string]string) templ.Attributes

OnKeys creates a keyboard event handler for multiple keys. Usage: <input { templ.OnKeys(map[string]string{"Enter": "submit", "Escape": "cancel"}) } />

func OnKeyup

func OnKeyup(handler string) templ.Attributes

OnKeyup creates a keyup handler. Usage: <input { templ.OnKeyup("handleKeyup") } />

func OnMouseenter

func OnMouseenter(handler string) templ.Attributes

OnMouseenter creates a mouseenter handler. Usage: <div { templ.OnMouseenter("handleEnter") }></div>

func OnMouseleave

func OnMouseleave(handler string) templ.Attributes

OnMouseleave creates a mouseleave handler. Usage: <div { templ.OnMouseleave("handleLeave") }></div>

func OnShiftKey

func OnShiftKey(key string, handler string) templ.Attributes

OnShiftKey creates a handler for Shift + key combination. Usage: <input { templ.OnShiftKey("Tab", "focusPrev") } />

func OnSubmit

func OnSubmit(handler string) templ.Attributes

OnSubmit creates a submit handler with preventDefault. Usage: <form { templ.OnSubmit("handleSubmit") }></form>

func OnWithModifiers

func OnWithModifiers(event string, handler string, modifiers ...string) templ.Attributes

OnWithModifiers creates an event handler with modifiers. Usage: <button { templ.OnWithModifiers("click", "submit", "prevent", "stop") }>Submit</button>

func Once

func Once() templ.Attributes

Once creates a once modifier (handler runs only once). Usage: <button { templ.Once() } onclick="showWelcome">Welcome</button>

func Passive

func Passive() templ.Attributes

Passive creates a passive event listener modifier. Usage: <div { templ.Passive() } onscroll="handleScroll">Scrollable</div>

func Placeholder

func Placeholder(p string) templ.Attributes

Placeholder generates a placeholder attribute.

func PreventDefault

func PreventDefault() templ.Attributes

PreventDefault creates a preventDefault modifier attribute. Usage: <a href="/link" { templ.PreventDefault() } onclick="handleClick">Link</a>

func PropBinding

func PropBinding(prop string, key string) templ.Attributes

PropBinding creates a property binding. Usage: <input { templ.PropBinding("disabled", "isDisabled") } />

func PropsFromJSON

func PropsFromJSON(data string) (map[string]any, error)

PropsFromJSON parses JSON into a props map.

func PropsToJSON

func PropsToJSON(props map[string]any) (string, error)

PropsToJSON serializes props to JSON.

func ProvideState

func ProvideState(ctx context.Context, key string, value any) context.Context

ProvideState provides state to child components via context.

func Raw

func Raw(html string) templ.Component

Raw renders raw HTML content.

func Readonly

func Readonly(readonly bool) templ.Attributes

Readonly generates a readonly attribute.

func Rel

func Rel(rel string) templ.Attributes

Rel generates a rel attribute.

func RenderChildren

func RenderChildren(c *Component) templ.Component

RenderChildren renders the children slot.

func RenderComponent

func RenderComponent(c *Component, content templ.Component) templ.Component

RenderComponent renders a component with its state.

func RenderLayout

func RenderLayout(layout LayoutFunc, props LayoutProps) templ.Component

RenderLayout renders a single layout with props.

func RenderSlot

func RenderSlot(c *Component, name string, fallback templ.Component) templ.Component

RenderSlot renders a named slot with fallback.

func Required

func Required(required bool) templ.Attributes

Required generates a required attribute.

func Role

func Role(role string) templ.Attributes

Role generates a role attribute.

func RuntimeScript

func RuntimeScript(src string) templ.Component

RuntimeScript returns the script tag for the GoSPA client runtime.

func RuntimeScriptInline

func RuntimeScriptInline(code string) templ.Component

RuntimeScriptInline returns an inline script tag with the runtime code.

func SPAPage

func SPAPage(config SPAConfig) templ.Component

SPAPage returns an HTML page configured for SPA mode.

func SafeAttr

func SafeAttr(s string) template.HTMLAttr

SafeAttr marks a string as a safe attribute value.

func SafeHTML

func SafeHTML(s string) template.HTML

SafeHTML marks a string as safe HTML.

func ScrollTo

func ScrollTo(elementID string) templ.Attributes

ScrollTo creates a scroll-to-element handler. Usage: <button { templ.ScrollTo("section-1") }>Scroll to Section 1</button>

func ScrollToTop

func ScrollToTop() templ.Attributes

ScrollToTop creates a scroll-to-top handler. Usage: <button { templ.ScrollToTop() }>Back to Top</button>

func Selected

func Selected(selected bool) templ.Attributes

Selected generates a selected attribute.

func Self

func Self() templ.Attributes

Self creates a self modifier (only triggers if event.target is the element itself). Usage: <div { templ.Self() } onclick="handleClick">Click me only</div>

func SerializeIslands

func SerializeIslands() (string, error)

SerializeIslands serializes all islands for client transfer.

func ServerAction

func ServerAction(action string, params string) templ.Attributes

ServerAction creates a server action handler. Usage: <button { templ.ServerAction("deleteItem", "itemId=123") }>Delete</button>

func ServerActionJSON

func ServerActionJSON(action string, params map[string]any) templ.Attributes

ServerActionJSON creates a server action handler with JSON params. Usage: <button { templ.ServerActionJSON("updateItem", map[string]any{"id": 123, "name": "test"}) }>Update</button>

func ServerOnly

func ServerOnly(content templ.Component) templ.Component

ServerOnly renders content only on the server (no hydration).

func SetState

func SetState(key string, value string) templ.Attributes

SetState creates a handler to set state directly. Usage: <button { templ.SetState("filter", "active") }>Active</button>

func ShowBinding

func ShowBinding(key string) templ.Attributes

ShowBinding creates a show/hide binding based on boolean state. Usage: <div { templ.ShowBinding("isVisible") }></div>

func SlotPlaceholder added in v0.1.4

func SlotPlaceholder(name string) string

SlotPlaceholder returns the raw placeholder comment string for a given slot name. This is used internally by the PPR streamer to locate replacement positions in the cached shell HTML.

func SpreadProps

func SpreadProps(props map[string]any) templ.Attributes

SpreadProps spreads props as attributes.

func Src

func Src(src string) templ.Attributes

Src generates a src attribute.

func StopPropagation

func StopPropagation() templ.Attributes

StopPropagation creates a stopPropagation modifier attribute. Usage: <div { templ.StopPropagation() } onclick="handleClick">Click</div>

func Style

func Style(styles map[string]string) templ.Attributes

Style generates a style attribute from a map.

func StyleBinding

func StyleBinding(property string, key string) templ.Attributes

StyleBinding creates a style binding. Usage: <div { templ.StyleBinding("color", "textColor") }></div>

func Suspense

func Suspense(loader func() (templ.Component, error), fallback templ.Component) templ.Component

Suspense renders content with a fallback while loading.

func Switch

func Switch(cases ...SwitchCase) templ.Component

Switch renders the first matching case.

func TabIndex

func TabIndex(index int) templ.Attributes

TabIndex generates a tabindex attribute.

func Target

func Target(target string) templ.Attributes

Target generates a target attribute.

func Text

func Text(key string) templ.Attributes

Text creates a text content binding. Usage: <span { templ.Text("message") }></span>

func TextContent

func TextContent(text string) templ.Component

TextContent renders text content (HTML escaped).

func Throttled

func Throttled(event string, handler string, ms int) templ.Attributes

Throttled creates a throttled event handler. Usage: <input { templ.Throttled("input", "search", 100) } />

func Title

func Title(title string) templ.Component

Title returns a title tag.

func Toggle

func Toggle(key string) templ.Attributes

Toggle creates a toggle handler for boolean state. Usage: <button { templ.Toggle("isExpanded") }>Toggle</button>

func TwoWayBind

func TwoWayBind(key string) templ.Attributes

TwoWayBind creates a two-way binding for form elements. Usage: <input { templ.TwoWayBind("name") } />

func Type

func Type(t string) templ.Attributes

Type generates a type attribute.

func Value

func Value(key string) templ.Attributes

Value creates a value binding for form elements. Usage: <input { templ.Value("name") } />

func ValueAttr

func ValueAttr(v string) templ.Attributes

ValueAttr generates a value attribute.

func When

func When(condition bool, component templ.Component) templ.Component

When renders a component conditionally.

func WhenElse

func WhenElse(condition bool, ifTrue, ifFalse templ.Component) templ.Component

WhenElse renders one of two components based on a condition.

func WithComponentContext

func WithComponentContext(ctx context.Context, cc *ComponentContext) context.Context

WithComponentContext sets the component context in the Go context.

func WithLayoutContext

func WithLayoutContext(ctx context.Context, lc *LayoutContext) context.Context

WithLayoutContext sets the layout context in the Go context.

func WithPPRShellBuild added in v0.1.4

func WithPPRShellBuild(ctx context.Context) context.Context

WithPPRShellBuild attaches a marker to ctx indicating that the current render pass is building the PPR shell (not a live request render).

Types

type Binding

type Binding struct {
	// Type of binding.
	Type BindingType
	// Key is the state key.
	Key string
	// Attr is the attribute name for attr/prop bindings.
	Attr string
	// Transform is an optional transform function name.
	Transform string
}

Binding represents a reactive DOM binding.

type BindingType

type BindingType string

BindingType represents the type of DOM binding.

const (
	// TextBind binds to textContent.
	TextBind BindingType = "text"
	// HTMLBind binds to innerHTML.
	HTMLBind BindingType = "html"
	// ValueBind binds to input value.
	ValueBind BindingType = "value"
	// CheckedBind binds to checkbox/radio checked state.
	CheckedBind BindingType = "checked"
	// ClassBind binds to CSS classes.
	ClassBind BindingType = "class"
	// StyleBind binds to inline styles.
	StyleBind BindingType = "style"
	// AttrBind binds to a custom attribute.
	AttrBind BindingType = "attr"
	// PropBind binds to a DOM property.
	PropBind BindingType = "prop"
	// ShowBind shows/hides element based on boolean.
	ShowBind BindingType = "show"
	// IfBind conditionally renders element.
	IfBind BindingType = "if"
)

type Component

type Component struct {
	// ID is the unique component identifier.
	ID string
	// Name is the component name for debugging.
	Name string
	// State holds the reactive state.
	State *ComponentState
	// Props are the component's input properties.
	Props map[string]any
	// Children is the component's children snippet.
	Children templ.Component
	// Slots are named slots for composition.
	Slots map[string]templ.Component
	// contains filtered or unexported fields
}

Component represents a GoSPA component with reactive state.

func DefineComponent

func DefineComponent(name string, render ComponentFunc, opts ...ComponentOption) *Component

DefineComponent defines a new component with a render function.

func GetCurrentComponent

func GetCurrentComponent(ctx context.Context) *Component

GetCurrentComponent gets the current component from context.

func GetParentComponent

func GetParentComponent(ctx context.Context) *Component

GetParentComponent gets the parent component from context.

func NewComponent

func NewComponent(name string, opts ...ComponentOption) *Component

NewComponent creates a new component with the given name and options.

func (*Component) AddState

func (c *Component) AddState(key string, value any) *state.Rune[any]

AddState adds a reactive state value to the component.

func (*Component) Attrs

func (c *Component) Attrs() templ.Attributes

Attrs returns the component's data attributes.

func (*Component) Destroy

func (c *Component) Destroy()

Destroy triggers the destroy lifecycle hook.

func (*Component) GetProp

func (c *Component) GetProp(key string, defaultValue any) any

GetProp gets a prop value by key with a default.

func (*Component) GetSlot

func (c *Component) GetSlot(name string) templ.Component

GetSlot gets a slot by name.

func (*Component) GetState

func (c *Component) GetState(key string) (any, bool)

GetState gets a state value by key.

func (*Component) HasSlot

func (c *Component) HasSlot(name string) bool

HasSlot checks if a slot exists.

func (*Component) InitScript

func (c *Component) InitScript() templ.Component

InitScript returns the component initialization script.

func (*Component) Mount

func (c *Component) Mount()

Mount triggers the mount lifecycle hook.

func (*Component) Render

func (c *Component) Render(ctx context.Context, w io.Writer) error

Render renders the component's children.

func (*Component) RenderSlot

func (c *Component) RenderSlot(ctx context.Context, w io.Writer, name string) error

RenderSlot renders a named slot.

func (*Component) SetState

func (c *Component) SetState(key string, value any)

SetState sets a state value by key.

func (*Component) ToJSON

func (c *Component) ToJSON() (string, error)

ToJSON serializes the component state to JSON.

func (*Component) Update

func (c *Component) Update()

Update triggers the update lifecycle hook.

func (*Component) UpdateState

func (c *Component) UpdateState(key string, fn func(any) any)

UpdateState updates a state value using a function.

type ComponentContext

type ComponentContext struct {
	// Component is the current component.
	Component *Component
	// Parent is the parent component context.
	Parent *ComponentContext
	// Context is the Go context.
	Context context.Context
}

ComponentContext provides context for components.

func GetContext

func GetContext(ctx context.Context) *ComponentContext

GetContext gets the component context from the Go context.

type ComponentFunc

type ComponentFunc func(*Component) templ.Component

ComponentFunc is a function that creates a templ.Component.

type ComponentOption

type ComponentOption func(*Component)

ComponentOption is a function that configures a component.

func OnDestroy

func OnDestroy(fn func()) ComponentOption

OnDestroy sets the destroy lifecycle hook.

func OnMount

func OnMount(fn func()) ComponentOption

OnMount sets the mount lifecycle hook.

func OnUpdate

func OnUpdate(fn func()) ComponentOption

OnUpdate sets the update lifecycle hook.

func WithChildren

func WithChildren(children templ.Component) ComponentOption

WithChildren sets the component children.

func WithProps

func WithProps(props map[string]any) ComponentOption

WithProps sets the component props.

func WithSlot

func WithSlot(name string, content templ.Component) ComponentOption

WithSlot sets a named slot.

func WithSlots

func WithSlots(slots map[string]templ.Component) ComponentOption

WithSlots sets multiple named slots.

type ComponentState

type ComponentState struct {
	// ID is the unique component identifier.
	ID string
	// State is the reactive state map.
	State *state.StateMap
	// Bindings are the component's bindings.
	Bindings map[string]Binding
}

ComponentState represents state for a component.

func NewComponentState

func NewComponentState(id string) *ComponentState

NewComponentState creates a new component state container.

func (*ComponentState) AddBinding

func (cs *ComponentState) AddBinding(key string, binding Binding)

AddBinding adds a binding to the component.

func (*ComponentState) AddRune

func (cs *ComponentState) AddRune(key string, r *state.Rune[any]) *ComponentState

AddRune adds a rune to the component state.

func (*ComponentState) GetRune

func (cs *ComponentState) GetRune(key string) (*state.Rune[any], bool)

GetRune gets a rune by key.

func (*ComponentState) InitScript

func (cs *ComponentState) InitScript() templ.Component

InitScript generates the component initialization script.

func (*ComponentState) RenderBindings

func (cs *ComponentState) RenderBindings() templ.Attributes

RenderBindings renders all bindings as data attributes.

func (*ComponentState) StateAttrs

func (cs *ComponentState) StateAttrs() templ.Attributes

StateAttrs generates data attributes for component state initialization. Usage: <div { cs.StateAttrs() }></div>

func (*ComponentState) ToJSON

func (cs *ComponentState) ToJSON() (string, error)

ToJSON serializes the component state to JSON.

type DeferredIsland

type DeferredIsland struct {
	Name        string
	Placeholder templ.Component
	Loader      func() (templ.Component, error)
}

DeferredIsland represents an island to be loaded later.

type EventHandler

type EventHandler struct {
	// Event is the event name (click, input, change, etc.)
	Event string
	// Handler is the handler function name or expression.
	Handler string
	// Modifiers are event modifiers (prevent, stop, capture, etc.)
	Modifiers []string
	// Debounce is the debounce duration in milliseconds (0 = no debounce).
	Debounce int
	// Throttle is the throttle duration in milliseconds (0 = no throttle).
	Throttle int
}

EventHandler represents a client-side event handler.

type HeadElement

type HeadElement struct {
	Tag      string            // e.g., "title", "meta", "link", "script", "style"
	Attrs    map[string]string // HTML attributes
	Content  string            // Inner content (for title, script, style)
	Key      string            // Unique key for deduplication (optional)
	Priority int               // Higher priority renders first
}

HeadElement represents an element in the document head.

type HeadManager

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

HeadManager manages head elements for SPA navigation. It renders elements with data-gospa-head attribute for client-side updates.

func NewHeadManager

func NewHeadManager() *HeadManager

NewHeadManager creates a new head manager.

func (*HeadManager) AddHeadElement

func (h *HeadManager) AddHeadElement(el HeadElement) *HeadManager

AddHeadElement adds a custom head element.

func (*HeadManager) AddHeadInlineScript

func (h *HeadManager) AddHeadInlineScript(content string) *HeadManager

AddHeadInlineScript adds an inline script.

func (*HeadManager) AddHeadInlineStyle

func (h *HeadManager) AddHeadInlineStyle(css string) *HeadManager

AddHeadInlineStyle adds inline CSS.

func (h *HeadManager) AddHeadLink(rel, href string, extraAttrs ...map[string]string) *HeadManager

AddHeadLink adds a link tag.

func (*HeadManager) AddHeadMeta

func (h *HeadManager) AddHeadMeta(name, content string) *HeadManager

AddHeadMeta adds a meta tag.

func (*HeadManager) AddHeadMetaProperty

func (h *HeadManager) AddHeadMetaProperty(property, content string) *HeadManager

AddHeadMetaProperty adds a meta property tag (Open Graph).

func (*HeadManager) AddHeadScript

func (h *HeadManager) AddHeadScript(src string, async, defer_ bool) *HeadManager

AddHeadScript adds a script tag.

func (*HeadManager) AddHeadStyle

func (h *HeadManager) AddHeadStyle(href string) *HeadManager

AddHeadStyle adds a stylesheet link.

func (*HeadManager) Render

func (h *HeadManager) Render() templ.Component

Render renders all head elements as a component.

func (*HeadManager) SetHeadTitle

func (h *HeadManager) SetHeadTitle(title string) *HeadManager

SetHeadTitle sets the page title.

type IslandOptions

type IslandOptions struct {
	// HydrationMode determines when the island hydrates.
	HydrationMode component.IslandHydrationMode
	// Priority affects loading order.
	Priority component.IslandPriority
	// ClientOnly skips SSR entirely.
	ClientOnly bool
	// ServerOnly renders HTML without client JS.
	ServerOnly bool
	// LazyThreshold for visible mode - margin in pixels.
	LazyThreshold int
	// DeferDelay for idle mode - max delay in ms.
	DeferDelay int
	// Class adds custom CSS classes.
	Class string
	// Tag specifies the wrapper element tag.
	Tag string
}

IslandOptions configures island rendering behavior.

type IslandRenderer

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

IslandRenderer handles island rendering operations.

func NewIslandRenderer

func NewIslandRenderer(registry *component.IslandRegistry) *IslandRenderer

NewIslandRenderer creates a new island renderer.

type Layout

type Layout struct {
	// Name is the layout name for debugging.
	Name string
	// Render is the layout render function.
	Render LayoutFunc
	// Loader is the optional data loader.
	Loader LayoutLoader
}

Layout represents a layout with its renderer and optional data loader.

func LayoutComponent

func LayoutComponent(name string, render LayoutFunc, loader ...LayoutLoader) *Layout

LayoutComponent creates a layout component from a render function.

func RootLayout

func RootLayout(title string, head, body templ.Component) *Layout

RootLayout creates a root layout with common HTML structure.

func WrapLayout

func WrapLayout(name string, component templ.Component) *Layout

WrapLayout wraps an existing templ.Component as a layout.

type LayoutChain

type LayoutChain struct {
	// Layouts are ordered from root to leaf.
	Layouts []*Layout
	// Page is the final page component.
	Page templ.Component
	// Error is the optional error component.
	Error templ.Component
}

LayoutChain represents a chain of nested layouts.

func NewLayoutChain

func NewLayoutChain(page templ.Component, layouts ...*Layout) *LayoutChain

NewLayoutChain creates a new layout chain.

func (*LayoutChain) Render

func (lc *LayoutChain) Render(ctx context.Context, w io.Writer, params map[string]string, path string) error

Render renders the layout chain with the given context.

func (*LayoutChain) WithError

func (lc *LayoutChain) WithError(error templ.Component) *LayoutChain

WithError sets the error component for the layout chain.

type LayoutContext

type LayoutContext struct {
	// Chain is the current layout chain.
	Chain *LayoutChain
	// Params are the route parameters.
	Params map[string]string
	// Path is the current route path.
	Path string
	// Data is accumulated layout data.
	Data map[string]any
}

LayoutContext provides context for layout rendering.

func GetLayoutContext

func GetLayoutContext(ctx context.Context) *LayoutContext

GetLayoutContext gets the layout context from the Go context.

type LayoutFunc

type LayoutFunc func(LayoutProps) templ.Component

LayoutFunc is a function that renders a layout with props.

type LayoutLoader

type LayoutLoader interface {
	// Load loads data for the layout.
	Load(ctx context.Context, params map[string]string) (map[string]any, error)
}

LayoutLoader is an interface for loading layout data. Similar to SvelteKit's +layout.server.js load function.

type LayoutLoaderFunc

type LayoutLoaderFunc func(ctx context.Context, params map[string]string) (map[string]any, error)

LayoutLoaderFunc is a function adapter for LayoutLoader.

func (LayoutLoaderFunc) Load

func (f LayoutLoaderFunc) Load(ctx context.Context, params map[string]string) (map[string]any, error)

Load implements LayoutLoader.

type LayoutProps

type LayoutProps struct {
	// Data is the layout data from loader functions.
	Data map[string]any
	// Children is the content to render inside the layout.
	Children templ.Component
	// Slots contains named slots for composition.
	Slots map[string]templ.Component
	// Params are the route parameters.
	Params map[string]string
	// Path is the current route path.
	Path string
}

LayoutProps represents props passed to a layout component. Similar to Svelte's $props() for layouts.

func (LayoutProps) GetParam

func (p LayoutProps) GetParam(key string, defaultValue ...string) string

GetParam gets a route parameter by key with optional default.

func (LayoutProps) GetProp

func (p LayoutProps) GetProp(key string, defaultValue ...any) any

GetProp gets a data prop by key with optional default.

func (LayoutProps) GetSlot

func (p LayoutProps) GetSlot(name string, fallback ...templ.Component) templ.Component

GetSlot gets a slot by name with optional fallback.

func (LayoutProps) HasSlot

func (p LayoutProps) HasSlot(name string) bool

HasSlot checks if a slot exists.

func (LayoutProps) RenderChildren

func (p LayoutProps) RenderChildren() templ.Component

RenderChildren renders the children content.

func (LayoutProps) WithData

func (p LayoutProps) WithData(data map[string]any) LayoutProps

WithLayoutData adds data to layout props.

func (LayoutProps) WithSlot

func (p LayoutProps) WithSlot(name string, content templ.Component) LayoutProps

WithSlot adds a named slot to layout props.

type MetaTag

type MetaTag struct {
	Name    string
	Content string
}

MetaTag represents an HTML meta tag.

type NestedLayout

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

NestedLayout creates a nested layout structure. This is useful for building layouts programmatically.

func NewNestedLayout

func NewNestedLayout(outer *Layout) *NestedLayout

NewNestedLayout creates a new nested layout.

func (*NestedLayout) Build

func (n *NestedLayout) Build(page templ.Component) *LayoutChain

Build builds the layout chain from the nested structure.

func (*NestedLayout) Nest

func (n *NestedLayout) Nest(inner *Layout) *NestedLayout

Nest adds an inner layout.

type SPAConfig

type SPAConfig struct {
	Lang        string
	Title       string
	Meta        []MetaTag
	Stylesheets []string
	Head        templ.Component
	Body        templ.Component
	RootID      string
	RuntimeSrc  string
	AutoInit    bool
}

SPAConfig configures an SPA page.

type Slot

type Slot struct {
	Name    string
	Content templ.Component
}

Slot is a helper for defining slot content.

func NewSlot

func NewSlot(name string, content templ.Component) Slot

Slot creates a new slot.

type Slots

type Slots []Slot

Slots is a collection of slots.

func (Slots) ToMap

func (s Slots) ToMap() map[string]templ.Component

ToMap converts slots to a map.

type Snippet

type Snippet[T any] func(params T) templ.Component

Snippet defines a reusable template chunk with typed parameters

type StreamChunk

type StreamChunk struct {
	Type    string         `json:"type"`    // "html", "island", "script", "state", "error"
	ID      string         `json:"id"`      // Island ID or chunk identifier
	Content string         `json:"content"` // HTML content
	Data    map[string]any `json:"data"`    // Additional data (props, state, etc.)
}

StreamChunk represents a chunk of streamed content.

type StreamOptions

type StreamOptions struct {
	// EnableProgressiveHydration enables progressive island hydration.
	EnableProgressiveHydration bool
	// CriticalIslands are islands to render immediately.
	CriticalIslands []string
	// DeferBelowFold defers islands below the fold.
	DeferBelowFold bool
	// MaxBufferSize is the max buffer before flushing.
	MaxBufferSize int
}

StreamOptions configures streaming behavior.

type StreamRenderer

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

StreamRenderer handles streaming SSR operations.

func NewStreamRenderer

func NewStreamRenderer(config StreamRendererConfig) *StreamRenderer

NewStreamRenderer creates a new streaming renderer.

func (*StreamRenderer) StreamComponent

func (sr *StreamRenderer) StreamComponent(
	ctx context.Context,
	component templ.Component,
	w io.Writer,
	flusher interface{ Flush() error },
	opts StreamOptions,
) error

StreamComponent streams a component with progressive enhancement.

func (*StreamRenderer) StreamError

func (sr *StreamRenderer) StreamError(sw *StreamWriter, err error) error

StreamError streams an error to the client.

func (*StreamRenderer) StreamScript

func (sr *StreamRenderer) StreamScript(sw *StreamWriter, script string) error

StreamScript streams a script to the client.

func (*StreamRenderer) StreamState

func (sr *StreamRenderer) StreamState(sw *StreamWriter, id string, state map[string]any) error

StreamState streams state updates to the client.

type StreamRendererConfig

type StreamRendererConfig struct {
	FlushInterval  time.Duration
	BufferSize     int
	IslandRegistry *component.IslandRegistry
}

StreamRendererConfig configures the stream renderer.

type StreamWriter

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

StreamWriter handles writing streamed content.

func NewStreamWriter

func NewStreamWriter(w io.Writer, flusher interface{ Flush() error }, bufferSize int) *StreamWriter

NewStreamWriter creates a new stream writer.

func (*StreamWriter) Close

func (sw *StreamWriter) Close() error

Close closes the stream writer.

func (*StreamWriter) Flush

func (sw *StreamWriter) Flush() error

Flush flushes pending content.

func (*StreamWriter) Write

func (sw *StreamWriter) Write(p []byte) (n int, err error)

Write writes content to the stream.

func (*StreamWriter) WriteChunk

func (sw *StreamWriter) WriteChunk(chunk StreamChunk)

WriteChunk queues a chunk for streaming.

type SwitchCase

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

SwitchCase represents a case in a switch.

func Case

func Case(condition bool, component templ.Component) SwitchCase

Case creates a switch case.

func Default

func Default(component templ.Component) SwitchCase

Default creates a default switch case.

Jump to

Keyboard shortcuts

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