Skip to main content
Ctrl+K
FSharp.ViewEngine · DesignFSharp.ViewEngine · Key FeaturesFSharp.ViewEngine · Quick ExampleFSharp.ViewEngine · Getting StartedCore installation · Using .NET CLICore installation · Using Paket CLICore installation · Runtime SupportCore installation · Source DebuggingCore installation · Next StepsBuild your first view · Create the viewBuild your first view · Render the viewBuild your first view · Reuse componentsBuild your first view · NextElements and attributes · ElementsElements and attributes · AttributesElements and attributes · Mixed contentElements and attributes · Generic escape hatchesComposition and control flow · Functions as componentsComposition and control flow · Conditional contentComposition and control flow · SequencesRendering · FragmentsRendering · DocumentsRendering · Application boundariesEncoding and trusted content · Encoded by defaultEncoding and trusted content · Trusted raw contentEncoding and trusted content · Trusted names and expressionsAccessibility · Prefer native HTMLAccessibility · Names and relationshipsAccessibility · ARIA coverageAccessibility · Test behaviorCustom Elements & Attributes · Trusted Content BoundariesCustom Elements & Attributes · Custom ElementsCustom Elements & Attributes · elCustom Elements & Attributes · elVoidCustom Elements & Attributes · Nested Web ComponentsCustom Elements & Attributes · Custom AttributesCustom Elements & Attributes · _attrCustom Elements & Attributes · Key-value attributeCustom Elements & Attributes · Boolean attributeCustom Elements & Attributes · Combining with Built-in AttributesCustom Elements & Attributes · Extending the Html TypeCustom Elements & Attributes · Adding Custom ElementsCustom Elements & Attributes · Adding Custom AttributesCustom Elements & Attributes · Design System ExampleCustom Elements & Attributes · Shoelace ExampleSVG · Support PolicySVG · SetupSVG · Element ReferenceSVG · Numeric and Length ValuesSVG · Icon ExampleSVG · Chart and Text ExampleSVG · Gradients, Clipping, Masking, and ReuseSVG · AccessibilitySVG · Linking and NamespacesSVG · Attribute ReferenceSVG · Unsupported SVGDatastar · SetupDatastar · Core AttributesDatastar · data-signalsDatastar · data-bindDatastar · data-computedDatastar · data-effectDatastar · data-showDatastar · data-textDatastar · data-attrDatastar · data-classDatastar · data-styleDatastar · data-initDatastar · data-onDatastar · data-on-intersectDatastar · data-on-intervalDatastar · data-on-signal-patchDatastar · data-on-signal-patch-filterDatastar · data-indicatorDatastar · data-refDatastar · data-json-signalsDatastar · data-ignoreDatastar · data-ignore-morphDatastar · data-preserve-attrDatastar · Pro AttributesDatastar · data-animateDatastar · data-custom-validityDatastar · data-match-mediaDatastar · data-on-rafDatastar · data-on-resizeDatastar · data-persistDatastar · data-query-stringDatastar · data-replace-urlDatastar · data-scroll-into-viewDatastar · data-view-transitionDatastar · Trusted ExpressionsDatastar · Content Security PolicyDatastar · Complete ExampleHTMX · SetupHTMX · Request MethodsHTMX · hx-getHTMX · hx-postHTMX · hx-putHTMX · hx-patchHTMX · hx-deleteHTMX · Request Data and ConfigurationHTMX · hx-encodingHTMX · hx-headersHTMX · hx-includeHTMX · hx-paramsHTMX · hx-requestHTMX · hx-valsHTMX · Targeting and SwappingHTMX · hx-targetHTMX · hx-selectHTMX · hx-select-oobHTMX · hx-swapHTMX · hx-swap-oobHTMX · hx-preserveHTMX · Requests in FlightHTMX · hx-indicatorHTMX · hx-disabled-eltHTMX · hx-syncHTMX · hx-validateHTMX · Triggering and InteractionHTMX · hx-triggerHTMX · hx-confirmHTMX · hx-promptHTMX · hx-onHTMX · Navigation and HistoryHTMX · hx-boostHTMX · hx-push-urlHTMX · hx-replace-urlHTMX · hx-historyHTMX · hx-history-eltHTMX · Inheritance and ProcessingHTMX · hx-disableHTMX · hx-disinheritHTMX · hx-inheritHTMX · hx-extHTMX · Generic and Deprecated AttributesHTMX · Complete ExampleAlpine.js · SetupAlpine.js · Core DirectivesAlpine.js · x-dataAlpine.js · x-initAlpine.js · x-showAlpine.js · x-bindAlpine.js · x-onAlpine.js · x-textAlpine.js · x-htmlAlpine.js · x-modelAlpine.js · x-modelableAlpine.js · x-forAlpine.js · x-transitionAlpine.js · x-effectAlpine.js · x-ignoreAlpine.js · x-refAlpine.js · x-cloakAlpine.js · x-teleportAlpine.js · x-ifAlpine.js · x-idAlpine.js · Plugin DirectivesAlpine.js · x-maskAlpine.js · x-intersectAlpine.js · x-resizeAlpine.js · x-collapseAlpine.js · x-trapAlpine.js · x-anchorAlpine.js · x-sortAlpine.js · Plugins Without Directive HelpersAlpine.js · Trusted ExpressionsAlpine.js · Complete ExampleTailwind Plus Elements · SetupTailwind Plus Elements · Shared AttributesTailwind Plus Elements · AutocompleteTailwind Plus Elements · Command PaletteTailwind Plus Elements · Copy ButtonTailwind Plus Elements · DialogTailwind Plus Elements · DisclosureTailwind Plus Elements · Dropdown MenuTailwind Plus Elements · PopoverTailwind Plus Elements · SelectTailwind Plus Elements · TabsTailwind Plus Elements · Runtime ReadinessComponents · Get startedComponents · ActionsComponents · FeedbackComponents · Data displayComponents · Form controlsComponents · NavigationComponents · OverlaysComponents · LayoutComponents · Code and diagramsComponent installation · Install the CLIComponent installation · Add componentsComponent installation · Install the build toolsComponent installation · Configure TailwindComponent installation · Import component JavaScriptComponent installation · Build and watchComponent installation · Serve and use the componentsComponent installation · Update installed componentsButton · InstallationButton · UsageButton · SizesButton · ColorsButton · VariantsButton · Uniform paddingButton · All color variantsButton · PendingButton · ChildrenButton · Icon-only variantsButton · Custom paletteButton · Primary buttonsButton · Secondary buttonsButton · Ghost buttonsButton · Native Ghost resetButton · Destructive buttonsButton · Destructive pendingButton · Disabled buttonsButton · Primary icon-onlyButton · Pending icon-onlyButton · Disabled icon-onlyButton · Datastar visibilityButton · Row actionsButton · Labels and focusButton · API referenceLink · InstallationLink · UsageLink · Text underlineLink · Inherited presentationLink · SizesLink · Uniform paddingLink · ColorsLink · VariantsLink · All color variantsLink · Icon-only variantsLink · Icon-only sizesLink · Native new-tab navigationLink · API referenceButton group · InstallationButton group · UsageButton group · Grouped actionsButton group · Native link segmentsButton group · Label and Select segmentsButton group · Custom controls and popup isolationButton group · Vertical orientationButton group · API referenceDropdown menu · InstallationDropdown menu · UsageDropdown menu · IconsDropdown menu · Keyboard hintsDropdown menu · CheckboxesDropdown menu · Radio choicesDropdown menu · Disabled itemsDropdown menu · Destructive actionDropdown menu · Outlined page actionDropdown menu · Custom native controlDropdown menu · Full context row and supporting descriptionsDropdown menu · Grouped states and refreshDropdown menu · Row actionsDropdown menu · API referenceToggle button · InstallationToggle button · UsageToggle button · PendingToggle button · DisabledToggle button · Content, sizes and variantsToggle button · API referenceToggle group · InstallationToggle group · UsageToggle group · Single selectionToggle group · Connected multiple and single-item groupsToggle group · Multiple, spaced and unavailableToggle group · SubmissionToggle group · Vertical orientationToggle group · API referenceBadge · InstallationBadge · UsageBadge · ColorsBadge · VariantsBadge · API referenceNotice · InstallationNotice · UsageNotice · ColorsNotice · VariantsNotice · Success with downloadNotice · WarningNotice · Error with recovery linkNotice · Announce an updateNotice · API referenceNotification · InstallationNotification · UsageNotification · Persistent with an actionNotification · Custom lifetimeNotification · AnnouncementsNotification · API referenceLoading indicator · InstallationLoading indicator · UsageLoading indicator · With visible labelLoading indicator · API referenceProgress · InstallationProgress · UsageProgress · IndeterminateProgress · CompleteProgress · FailedProgress · API referenceEmpty state · InstallationEmpty state · UsageEmpty state · Title onlyEmpty state · With recovery actionEmpty state · API referenceSkeleton · InstallationSkeleton · UsageSkeleton · TextSkeleton · Avatar rowSkeleton · CardSkeleton · Explicit dimensionsSkeleton · API referenceCallout · InstallationCallout · UsageCallout · API referenceIcon · InstallationIcon · UsageIcon · Heroicons familiesIcon · Brand logosIcon · Rendered-size overridesIcon · API referenceTable · InstallationTable · UsageTable · Comfortable rowsTable · Hover highlightingTable · With status valuesTable · With checkboxesTable · Scrollable rows and sticky headingsTable · Stacked on mobileTable · Sortable recordsTable · Hierarchical itemsTable · Row actionsTable · Empty stateTable · Infinite scrollTable · API referenceChart · InstallationChart · UsageChart · ColumnChart · Horizontal barChart · SankeyChart · Updating options and handling eventsChart · Empty dataChart · API referenceDescription list · InstallationDescription list · UsageDescription list · Three-column detailsDescription list · Four-column detailsDescription list · With supporting textDescription list · API referenceMetric · InstallationMetric · UsageMetric · With trend and statusMetric · With review statusMetric · Multiple metricsMetric · API referenceAvatar · InstallationAvatar · UsageAvatar · Fallbacks and sizesAvatar · ImageAvatar · Image unavailableAvatar · DecorativeAvatar · API referenceCopy and reveal · InstallationCopy and reveal · UsageCopy and reveal · Icon actionsCopy and reveal · Initially revealedCopy and reveal · API referenceDay calendar · InstallationDay calendar · UsageDay calendar · Overlapping sessionsDay calendar · Compact controlsDay calendar · Provisional time selectionDay calendar · API referenceWeek calendar · InstallationWeek calendar · UsageWeek calendar · Events and date navigationWeek calendar · Shared controls and event detailsWeek calendar · API referenceMonth calendar · InstallationMonth calendar · UsageMonth calendar · Events and date navigationMonth calendar · Compact monthMonth calendar · Single-date selectionMonth calendar · Clearable single dateMonth calendar · Current dateMonth calendar · Today shortcutMonth calendar · Date rangeMonth calendar · Bounds, unavailable dates and Monday startMonth calendar · Month and year selectorsMonth calendar · Busy availabilityMonth calendar · Read-only selectionMonth calendar · API referenceYear calendar · InstallationYear calendar · UsageYear calendar · Event indicators and date navigationYear calendar · API referenceKbd · InstallationKbd · UsageKbd · Shortcut groupKbd · API referenceSeparator · InstallationSeparator · UsageSeparator · Orientation and semanticsSeparator · API referenceCard · InstallationCard · UsageCard · Header and footerCard · With mediaCard · API referenceMessage · InstallationMessage · UsageMessage · Sender and receiverMessage · Metadata and actions without an avatarMessage · API referenceInput · InstallationInput · UsageInput · Consistent control sizesInput · With help textInput · RequiredInput · OptionalInput · Validation errorInput · Native searchInput · DisabledInput · Read-onlyInput · API referenceInput group · InstallationInput group · UsageInput group · IconInput group · SuffixInput group · Text addonsInput group · Icon and keyboard hintInput group · Addon popup keeps its own controlsInput group · Textarea header and footerInput group · Validation errorInput group · Checking with visible feedbackInput group · API referenceField · InstallationField · UsageField · Custom controlField · Responsive label and control rowsField · Semantic fieldsetField · Labels and focusField · API referenceTextarea · InstallationTextarea · UsageTextarea · Visually hidden labelTextarea · With instructionsTextarea · Validation errorTextarea · Read-onlyTextarea · DisabledTextarea · API referenceFile selection · InstallationFile selection · UsageFile selection · Multiple filesFile selection · ValidationFile selection · DisabledFile selection · API referenceTag input · InstallationTag input · UsageTag input · SubmissionTag input · ValidationTag input · PendingTag input · DisabledTag input · API referenceError summary · InstallationError summary · UsageError summary · API referenceSelect · InstallationSelect · UsageSelect · Custom items and groupsSelect · Multiple selectionSelect · Local searchSelect · Remote searchSelect · Form validationSelect · DisabledSelect · PendingSelect · API referenceTime picker · InstallationTime picker · UsageTime picker · 24-hour display and boundsTime picker · Disabled and read-onlyTime picker · API referenceDate picker · InstallationDate picker · UsageDate picker · Clearable single dateDate picker · Current dateDate picker · Today shortcutDate picker · Date rangeDate picker · Month and year selectorsDate picker · Bounds and unavailable datesDate picker · ValidationDate picker · PendingDate picker · DisabledDate picker · Read-onlyDate picker · API referenceCheckbox · InstallationCheckbox · UsageCheckbox · With help textCheckbox · IndeterminateCheckbox · Required confirmation with validationCheckbox · CheckedCheckbox · PendingCheckbox · DisabledCheckbox · API referenceSwitch · InstallationSwitch · UsageSwitch · With help textSwitch · Setting with submissionSwitch · PendingSwitch · DisabledSwitch · Validation errorSwitch · SizesSwitch · Stacked layoutSwitch · API referenceRadio group · InstallationRadio group · UsageRadio group · Option descriptionsRadio group · Horizontal orientationRadio group · Required choice with validationRadio group · PendingRadio group · DisabledRadio group · API referenceChoice cards · InstallationChoice cards · UsageChoice cards · Single choiceChoice cards · Multiple choicesChoice cards · ValidationChoice cards · API referenceField group · InstallationField group · UsageField group · Without descriptionField group · Disabled fieldsetField group · Horizontal fieldsField group · Responsive fieldsField group · API referenceBreadcrumbs · InstallationBreadcrumbs · UsageBreadcrumbs · Middle overflowBreadcrumbs · Available spaceBreadcrumbs · API referenceSide nav · InstallationSide nav · UsageSide nav · Sections and collapsible groupsSide nav · Header, context, content and footerSide nav · Nested navigation with badges and actionsSide nav · Expansion and scrollSide nav · API referenceTabs · InstallationTabs · UsageTabs · Server-owned selectionTabs · Underlined tabs with refreshTabs · Vertical, icons and disabled itemsTabs · API referencePagination · InstallationPagination · UsagePagination · Page navigationPagination · Numbers onlyPagination · Previous and next onlyPagination · API referenceCommand · InstallationCommand · UsageCommand · Groups, icons and shortcutsCommand · Contextual page linksCommand · Actions and disabled itemsCommand · Dialog paletteCommand · Empty resultsCommand · API referenceBottom navigation · InstallationBottom navigation · UsageBottom navigation · Four destinationsBottom navigation · Three destinationsBottom navigation · API referenceDialog · InstallationDialog · UsageDialog · Modal dialogDialog · Server-validated confirmationDialog · App-contained dialogDialog · Labels and focusDialog · API referenceDrawer · InstallationDrawer · UsageDrawer · NavigationDrawer · Standard detail drawerDrawer · Wide editing formDrawer · Start-side filtersDrawer · Top and bottom edgesDrawer · App-contained drawerDrawer · Labels and focusDrawer · API referenceFloating panel · InstallationFloating panel · UsageFloating panel · Minimized with restoreFloating panel · ChecklistFloating panel · API referencePopover · InstallationPopover · UsagePopover · With formPopover · Side and alignmentPopover · Custom native triggerPopover · API referenceTooltip · InstallationTooltip · UsageTooltip · Existing descriptionTooltip · Bottom placementTooltip · API referenceBrowser · InstallationBrowser · UsageBrowser · With an address barBrowser · Review controls and expansionBrowser · API referencePhone · InstallationPhone · UsagePhone · With screen contentPhone · Review controls and expansionPhone · API referenceResizable · InstallationResizable · UsageResizable · Horizontal split panelsResizable · Vertical split panelsResizable · API referenceSlide · InstallationSlide · UsageSlide · CoverSlide · API referencePresentation · InstallationPresentation · UsagePresentation · API referencePage header · InstallationPage header · UsagePage header · Title and page actionsPage header · API referenceSection header · InstallationSection header · UsageSection header · Description, actions and dividerSection header · API referenceSection · InstallationSection · UsageSection · Section spacingSection · API referenceDisclosure · InstallationDisclosure · UsageDisclosure · API referencePage top bar · InstallationPage top bar · UsagePage top bar · Full-width shell barPage top bar · API referenceCode block · InstallationCode block · Quick start with GiraffeCode block · Add syntax highlightingCode block · Optional Prism stylesheetCode block · F#Code block · PythonCode block · TypeScriptCode block · BashCode block · SQLCode block · Optional nonce CSPCode block · API referenceExample · InstallationExample · UsageExample · API referenceMermaid · InstallationMermaid · UsageMermaid · Sequence constructorsMermaid · API referenceF# API reference · InstallationF# API reference · UsageF# API reference · API referenceStandalone F# scripts · PrerequisitesStandalone F# scripts · Use the Core packageStandalone F# scripts · Install editable components into a scriptStandalone F# scripts · Compose the HTML pageStandalone F# scripts · Build and viewStandalone F# scripts · Keep source ownership explicitStandalone F# scripts · Next stepsGiraffe integration · Minimal ExampleGiraffe integration · How It WorksGiraffe integration · Title ElementsUsing signals · Bind a value and handle an actionUsing signals · Related examplesTheming · Apply a theme to a regionTheming · Override only what you needTheming · Scope CSS variables to a regionTheming · CSS-variable referenceTheming · Internal variablesTheming · Add an appearance pickerTheming · Theme APIBuild a presentation · Create a deckBuild a presentation · Compose slides with ordinary F#Build a presentation · Build and openBuild a presentation · Present in the browserBuild a presentation · Print or save as PDFBuild a presentation · Explore the complete exampleBenchmarks · Rendering performanceBenchmarks · EnvironmentBenchmarks · ReproduceExamples · Templates

Datastar

FSharp.ViewEngine exposes 31 typed attribute helpers through the Datastar type. The canonical examples use the pinned Datastar 1.0.4 runtime. Rocket-only attributes require the corresponding official bundle.

On this page

Setup

Open the Datastar type to access Datastar attributes:

open FSharp.ViewEngine
open type Html
open type Datastar

Modifier overloads accept an ordered list of modifier strings without the leading __. Modifier arguments follow the modifier name after a period:

input {
    _dataBind ("query", [ "event.input" ])
    _dataOn ("input", [ "debounce.200ms" ], "@get('/search')")
}

Keys, event names, and modifier strings become part of the HTML attribute name. Treat them as trusted application tokens; FSharp.ViewEngine does not validate or encode attribute names.

Core Attributes

data-signals

Create or patch signals with _dataSignals. Use object syntax for multiple signals, keyed syntax for one signal, and modifiers for casing or if-missing behavior.

div {
    _dataSignals "{count: 0, name: 'World'}"
    _dataSignals ("page", [ "ifmissing" ], "1")
}

data-bind

Create a two-way binding with _dataBind. Keyed bindings are presence-only; modifiers can select a property and synchronization events.

input {
    _type "search"
    _dataBind ("query", [ "prop.value"; "event.input.change" ])
}

data-computed

Create a read-only computed signal with _dataComputed.

div {
    _dataComputed ("double", "$count * 2")
    _dataComputed "{greeting: () => 'Hello, ' + $name}"
}

data-effect

Run a side-effect expression on initialization and whenever its signal dependencies change with _dataEffect.

div { _dataEffect "console.log($count)" }

data-show

Show or hide an element based on an expression with _dataShow.

div {
    _dataShow "$count > 0"
    "Count is positive"
}

data-text

Set an element's text content reactively with _dataText.

span { _dataText "$count" }

data-attr

Set one or more HTML attributes reactively with _dataAttr.

button {
    _dataAttr ("disabled", "$loading")
    _dataAttr "{'aria-busy': $loading}"
}

data-class

Toggle one or more classes with _dataClass. Keyed modifiers can override casing behavior.

div {
    _dataClass ("font-bold", "$strong")
    _dataClass ("my-class", [ "case.camel" ], "$active")
}

data-style

Set one or more inline style properties reactively with _dataStyle.

div {
    _dataStyle ("background-color", "$error ? 'red' : 'green'")
    _dataStyle "{display: $visible ? 'flex' : 'none'}"
}

data-init

Run an expression when an attribute is initialized with _dataInit. Delay and view-transition modifiers are supported.

div {
    _dataInit ([ "delay.500ms"; "viewtransition" ], "$ready = true")
}

data-on

Handle DOM events with _dataOn. Modifier order is preserved in the generated attribute name.

button {
    _dataOn ("click", [ "once"; "prevent" ], "$count++")
    "Increment"
}

data-on-intersect

Run an expression when an element enters or exits the viewport with _dataOnIntersect.

div {
    _dataOnIntersect ([ "once"; "threshold.25" ], "$visible = true")
}

data-on-interval

Run an expression on an interval with _dataOnInterval.

div {
    _dataOnInterval ([ "duration.500ms.leading" ], "$count++")
}

data-on-signal-patch

Run an expression when signals are patched with _dataOnSignalPatch. Timing modifiers can delay, debounce, or throttle the listener.

div {
    _dataOnSignalPatch ([ "debounce.500ms" ], "console.log(patch)")
}

data-on-signal-patch-filter

Filter signal patches using include and exclude regular expressions with _dataOnSignalPatchFilter.

div {
    _dataOnSignalPatchFilter "{include: /^count$/, exclude: /temp$/}"
}

data-indicator

Create a signal that tracks in-flight fetch requests with the presence-only _dataIndicator helper.

button {
    _dataIndicator "fetching"
    _dataOn ("click", "@get('/endpoint')")
    _dataAttr ("disabled", "$fetching")
}

data-ref

Create a signal containing a reference to an element with the presence-only _dataRef helper.

input { _dataRef "searchInput" }

data-json-signals

Render signals as JSON for debugging with _dataJsonSignals. Filters and terse output are optional.

pre { _dataJsonSignals () }
pre { _dataJsonSignals ([ "terse" ], "{include: /counter/}") }

data-ignore

Prevent Datastar from processing an element tree with _dataIgnore. Use the self modifier to ignore only the element.

div { _dataIgnore () }
div { _dataIgnore [ "self" ] }

data-ignore-morph

Prevent an element and its children from being processed during morphing with _dataIgnoreMorph.

div { _dataIgnoreMorph }

data-preserve-attr

Preserve one or more existing attribute values during morphing with _dataPreserveAttr.

details {
    _open true
    _dataPreserveAttr "open class"
}

Pro Attributes

Datastar Pro attributes require a Datastar Pro license. They are included as convenience helpers but are not part of the free core bundle.

data-animate

Animate a named element attribute reactively with the keyed _dataAnimate helper.

div {
    _dataAnimate ("opacity", "$visible ? 1 : 0")
}

data-custom-validity

Set a form control's custom validation message with _dataCustomValidity.

input {
    _dataBind "email"
    _dataCustomValidity "$email.includes('@') ? '' : 'Enter a valid email'"
}

data-match-media

Keep a signal synchronized with a media query using _dataMatchMedia.

div {
    _dataMatchMedia ("is-dark", "'prefers-color-scheme: dark'")
    _dataComputed ("theme", "$isDark ? 'dark' : 'light'")
}

data-on-raf

Run an expression on every animation frame with _dataOnRaf. Throttle modifiers can limit updates.

canvas {
    _dataOnRaf ([ "throttle.10ms" ], "draw()")
}

data-on-resize

Run an expression when an element's dimensions change with _dataOnResize.

div {
    _dataOnResize ([ "debounce.10ms" ], "$width = el.offsetWidth")
}

data-persist

Persist signals to local or session storage with _dataPersist. Use _dataPersistFilter for a default-key filter object.

div { _dataPersist () }
div { _dataPersist "settings" }
div { _dataPersist ("settings", [ "session" ]) }
div { _dataPersistFilter "{include: /theme/}" }

data-query-string

Synchronize signals with query-string parameters using _dataQueryString.

div {
    _dataQueryString ([ "filter"; "history" ], "{include: /search|page/}")
}

data-replace-url

Replace the browser URL without reloading using an evaluated expression passed to _dataReplaceUrl.

div { _dataReplaceUrl "`/page${$page}`" }

data-scroll-into-view

Scroll an element into view with _dataScrollIntoView. Behavior, alignment, and focus are controlled by modifiers.

div { _dataScrollIntoView () }
div { _dataScrollIntoView [ "smooth"; "vcenter"; "focus" ] }

data-view-transition

Set an element's view-transition-name reactively with _dataViewTransition.

div { _dataViewTransition "$transitionName" }

Trusted Expressions

Datastar expressions can execute JavaScript and backend actions. Attribute values are HTML-encoded by FSharp.ViewEngine, but encoding does not make untrusted expressions safe. Build expressions from trusted application code and never interpolate untrusted input into them.

Content Security Policy

Use Datastar's supported nonce CSP mode to retain expressions without unsafe-eval. Generate a cryptographically random nonce on the server for every full-page response, authorize it in the HTTP script-src policy, and put the same value in data-nonce on the html element. Datastar consumes the attribute and reuses that document nonce for expression compilation and scripts in element patches; patches do not need a new nonce.

html {
    _lang "en"
    _attr ("data-nonce", pageNonce)
    head {
        script { _type "module"; _src "/js/datastar.1.0.4.js" }
    }
    body {
        button { _dataOn ("click", "$count++"); "Increment" }
    }
}

The matching HTTP directive is script-src 'self' 'nonce-{pageNonce}', with connect-src 'self' for same-origin backend actions. Allow required consumer asset origins explicitly. A nonce does not authorize onclick attributes; use data-on instead. Components currently emit inline CSS variables and positioning, so the demonstrated style policy is style-src 'self' 'unsafe-inline', separate from the nonce-only script policy.

Nonces do not sanitize expressions. Keep expressions static and developer-controlled; serialize user values as data, never interpolate them into executable expressions. Signals are public and client-controlled, so avoid leaking secrets and validate all values and authorization on the server. Sanitize intentionally allowed user HTML; data-ignore can disable Datastar processing but is not an HTML sanitizer. See Datastar security guidance and the complete source ZIP host for a working integration.

Complete Example

An active search form using signals, binding, modifiers, an indicator, and a backend action:

div {
    _dataSignals ("query", [ "ifmissing" ], "''")
    _dataIndicator "searching"

    input {
        _type "search"
        _dataBind "query"
        _dataOn ("input", [ "debounce.200ms" ], "@get('/api/search')")
    }

    span { _dataShow "$searching"; "Searching..." }
    div { _id "search-results" }
}