# WildflowerJS: Full Documentation Corpus > WildflowerJS is a reactive JavaScript framework that uses standard HTML, CSS, and JavaScript without a build step, virtual DOM, or custom syntax. This file concatenates the complete documentation, including every example's HTML and JavaScript, for agents and tools that want the full corpus in one fetch. For a condensed single-fetch reference optimized for code generation, use https://www.wildflowerjs.com/llms.txt instead. Generated from the documentation pages. Do not edit by hand: scripts/generate-llms-full.cjs rebuilds it. ====================================================================== # SECTION: Getting Started ====================================================================== --- # Introduction to WildflowerJS > Source: https://www.wildflowerjs.com/getting-started/introduction Full reactivity using nothing but standard HTML and JavaScript. There is no proprietary syntax, build step, or vendor lock-in. Other frameworks require you to learn and commit to non-standard extensions: JSX, `.vue` single-file components, Svelte's `$:` labels, Angular's template compiler. WildflowerJS achieves the same reactive data binding, computed properties, conditional rendering, and list management using only `data-*` attributes and plain JavaScript. Things browsers already understand. **What You Get (Without Leaving Standard HTML & JS):** - Reactive state: mutate a property, the DOM updates automatically - Declarative binding via native `data-*` attributes: `data-bind`, `data-show`, `data-list`, `data-model`, `data-action` - Computed properties with automatic dependency tracking, including async ones that return a promise - List rendering with keyed reconciliation and nested lists, plus `data-pool` for high-frequency collections - Server data as a declaration: `data-query` fetches it, keeps it fresh, and sends writes with optimistic updates and rollback - Components, routing, SSR, and stores: all in one zero-dependency bundle - No build step or npm required: add a ` ``` #### Server Data as a Declaration Name a source, point an element at it, and say how fresh it should stay. The framework tracks loading and error states, refreshes on demand, discards responses that arrive out of order, and can poll, revalidate, or subscribe to a server push stream. Declare `to` and the same query sends changes back: `write()` puts them on screen immediately and rolls back the fields it changed if the server refuses. There is no query language to learn. Refinement is an ordinary computed property, and filtering happens client-side without a round trip. See [Data queries](https://www.wildflowerjs.com/docs/data-query). ```javascript wildflower.query('products', { from: '/api/products', key: 'id', refresh: ['focus', 'fresh:30'], // re-check on focus, at most every 30s to: '/api/products/:id', // where write() sends changes body: item => item // what to send }); ``` #### AI-Friendly by Construction LLMs like Claude, Gemini, and GPT are excellent at HTML, CSS, and JavaScript because those make up most of their training corpus. Framework-specific syntax is a thinner slice. WildflowerJS code is what AI generates cleanly without translation, and what humans can debug without sourcemaps. #### TypeScript Where It Counts Type-safe state, computed properties, and stores ship with the framework. Your existing TS skills transfer directly. The runtime `types` validator catches binding-shape drift in dev. Template-level type-checking for `data-bind` expressions is on the roadmap. ## Standards Compliance Web developers once treated validation as part of the job, and markup that failed the W3C validator was markup with bugs in it. Most front-end tools have since left that behind. Alpine's `x-data` and `@click`, Vue's `v-if` and `:class`, and htmx's `hx-get` are attributes the HTML standard does not define; browsers tolerate them, and the validator reports each one as an error. The standard gives authors one way to add their own attributes, `data-*`, and WildflowerJS reads nothing else. Its markup is valid HTML as written, with nothing to configure. Alpine and htmx can switch to `data-` names, Alpine through `Alpine.prefix()`, which turns off its `@` and `:` shorthands, but that is an option you choose, and their documentation is written in the other form. ## Zero Install. Zero Attack Surface. Every dependency you install lets a maintainer you have never met run scripts on your dev machine and in your CI. A typical React + Vite + UI-lib setup pulls in **300+ transitive packages** before you write a feature. Each one is a potential intrusion vector. [NPM worms](https://thehackernews.com/2026/04/self-propagating-supply-chain-worm.html), [OAuth chains compromising deploy platforms](https://www.trendmicro.com/en_us/research/26/d/vercel-breach-oauth-supply-chain.html), [postinstall hijacking](https://cloud.google.com/blog/topics/threat-intelligence/supply-chain-node-js): the supply chain is now where production code gets compromised, not the deploy. A WildflowerJS project has none of that surface. There is no `npm install`, postinstall script, or transitive package graph. The framework is one file you copy or pin by hash. ## Performance Without Compromise WildflowerJS writes to the DOM directly, which keeps both bulk list operations and single-value updates fast. ##### Direct DOM Updates No virtual DOM diffing overhead. State changes go straight to the elements that need updating, and no other node is touched. ##### Small Footprint The full framework ships as a single bundle that includes stores, routing, and SSR. No additional state management library required. ## Where WildflowerJS Shines WildflowerJS is built for reactive web development at any scale. It suits prototypes and production, solo builders and large teams. Some scenarios it's particularly well-suited to: #### Project Types - Customer-facing SaaS, internal tools, dashboards - Embedded widgets and interactive components - Documentation sites with live examples - Anywhere bundle size and load time matter #### Team Priorities - Shipping product over configuring tooling - Supply-chain risk treated as a real concern - AI-assisted code generation that runs as written - Skills that transfer when frameworks change Lite Boids Flocking 800+ autonomous agents at native frame rate. Every boid is a DOM element, drawn without canvas or WebGL. [Demo](https://www.wildflowerjs.com/demos/boids/) [Code](https://www.wildflowerjs.com/demos/view-source.html?file=boids/app.js) Core Kanban Board Drag-and-drop, modals, animated transitions, search filtering, and localStorage persistence. [Demo](https://www.wildflowerjs.com/demos/kanban-wf/) [Code](https://www.wildflowerjs.com/demos/view-source.html?file=kanban-wf/app.js) ## The Philosophy #### Trust the Platform Browsers have billions of hours of optimization behind them. The DOM isn't slow; inefficient abstractions are. We work with browser APIs, not against them. #### Separation of Concerns HTML describes structure. CSS describes presentation. JavaScript describes behavior. They work together but stay separate, so you can restyle a page without touching its behavior and change its behavior without touching the markup. #### Progressive Enhancement Your HTML works without JavaScript. The framework enhances it. If the script fails to load, the markup already in the document still renders. #### No Magic When you read WildflowerJS code, you understand what it does. No transpiler or build step sits between the file you edit and the code the browser runs. ## How Updates Work When state changes in WildflowerJS, updates flow directly to the DOM: **State Changes** this.count++ → **Proxy Marks Dependents** the bindings that read count → **DOM Updated** Element.textContent = 1 There's no intermediate representation, tree diffing, or reconciliation phase. The framework updates the one element that displays `count` directly. The marked bindings are flushed on a microtask rather than one at a time, so several writes in the same block produce a single DOM pass, before the browser paints. ### Element-Level Precision Each binding tracks its own dependencies. When `count` changes: - Only elements bound to `count` update - Other bindings don't re-evaluate - No parent components re-render - No children are touched This granularity comes from the **dependency graph**. Each `data-bind`, `data-show`, or `data-list` is its own effect that knows exactly what it depends on and which DOM element it controls. ## State Without Ceremony State in WildflowerJS is just a JavaScript object. No special wrappers or access patterns to memorize. ```javascript // Define state state: { count: 0, user: { name: 'Alice', score: 100 } } // Update state by assigning this.count++ this.user.name = 'Bob' this.user = { name: 'Charlie', score: 200 } // All of these trigger reactive updates automatically ``` Nested properties, array mutations, and complete replacements all work the same way: each one updates the bindings that read the changed value. ## Ready to Try It? The quickest way to start is with a single script tag: ```html

Hello, World!

``` That's a complete, reactive application. No build step or configuration; just HTML and JavaScript working together. [Get Started](https://www.wildflowerjs.com/getting-started/quickstart) [Learn Components](https://www.wildflowerjs.com/docs/components) --- # A JavaScript Framework With No Build Step > Source: https://www.wildflowerjs.com/getting-started/no-build-step There is no npm install, bundler config, or compiler between your code and the browser. Seven tiers, from a 44 KB interactive-widget build up to a full build with SSR and routing, and every one of them is still just a script tag. ## What "No Build Step" Actually Means A lot of frameworks say they're lightweight and still hand you a `package.json`. WildflowerJS doesn't. There is no compilation stage between the code you write and the code the browser runs: ##### No npm install Using WildflowerJS in a page requires zero packages. Point a `

Hello, World!

``` Save that as a `.html` file and open it. Typing in the input updates the greeting live. There's no second step where this code gets transformed into different code before it runs. This *is* the code that runs. ## What You Don't Give Up Most script-tag libraries earn "no build step" by staying small in scope, offering a bit of DOM sugar and maybe two-way binding. Add routing, server-side rendering, or shared state across components, and you are back to a bundler. WildflowerJS scales up instead of switching approaches. Every tier below is still a single ` ``` #### Script Tag Configuration Configure WildflowerJS directly from the script tag without any JavaScript: | Attribute | Values | Default | Description | | --- | --- | --- | --- | | data-debug | true , "" | false | Enable debug mode and verbose logging | | data-error-handling | log , throw , silent | log | How framework errors are handled | | data-auto-init | true , false | true | Automatically initialize on page load | | data-wf-prefix | true , false | false | Only process data-wf-* attributes | ```html ``` ### CDN ```html ``` ### ES Modules Every tier also ships as an ES module (from 1.5.1), named `.esm.min.js` beside the script-tag file. The default export is the framework instance, and the same `wildflower` global is registered, so a page behaves the same whichever file it loads. Use it from a ` ``` ```javascript // With a bundler or an import map: the package resolves the ES module for `import` import wildflower from 'wildflowerjs'; // core tier import wildflower from 'wildflowerjs/full'; // any tier: nano, mini-pool, mini, lite, spa, full ``` The named exports match the script-tag globals: `wildflower`, `WildflowerJS`, and on the SPA and Full tiers `RouteManager` (Full adds `SSRManager`). A `.esm.dev.js` twin carries the development diagnostics. ## Your First Component Create a simple interactive component in 2 steps: ### Step 1: HTML Structure ```html

Counter Example

Count: 0

``` ### Step 2: Component Definition ```javascript // The global 'wildflower' instance is created automatically wildflower.component('counter', { state: { count: 0 }, increment() { this.count++ }, decrement() { this.count-- }, reset() { this.count = 0 } }) ``` **That's it!** WildflowerJS auto-initializes and your counter is immediately reactive. **Note:** The framework creates a global `wildflower` instance automatically. You only need to create your own instance if you disable auto-init with `data-auto-init="false"`. ## Troubleshooting Common Issues ### Component Not Initializing If your component isn't initializing, make sure: - The component name in `data-component="name"` matches `wildflower.component('name', ...)` - Your component definition script runs after WildflowerJS loads - For dynamically added components, call `wildflower.scan()` ```html ``` ### Enable Debug Mode Enable debug mode during development for helpful console output: ```html ``` This provides detailed logging for component initialization, state changes, and binding updates. ### Flash of Empty Lists or Content If you see lists or bound content briefly appear empty before populating, the issue is **script placement**. Browsers progressively render HTML as it loads, so if your component HTML appears before the framework scripts, it will briefly render unpopulated. **Solution:** Place framework scripts at the start of ``, before your component HTML: ```html
``` **Script tags are blocking.** The browser waits for them to load and execute before continuing to parse the HTML. By placing framework scripts first, the framework is ready before the browser even sees your component HTML. **The alternative: `defer` plus `data-cloak`.** A blocking script costs you parse time, so [Performance Optimization](https://www.wildflowerjs.com/docs/optimization) recommends ` ``` That is a single file holding markup and logic together, which is what the term usually means. The two patterns below exist for *reuse*, meaning one component that several pages can load. ## Why a Component File Cannot Load Itself The browser loads JavaScript declaratively through `
``` **What you get:** state, methods, lifecycle, and styles all in one `.js` file. Browser executes the script tag with no special handling. Multiple instances cost nothing extra and the style injection is idempotent; drop more `data-component="counter"` elements wherever you need them. **When to reach for it:** default for almost everything. If you only need one of the two patterns, this is the one. **Trade-off:** the markup lives separately from the JS, which some teams prefer (designers can edit HTML without touching JS) and some prefer to colocate. If you want template + script + style in one file, see Pattern 2. ## Pattern 2: HTML Fragment File With Helper Template, styles, and registration script colocated in a single `.html` file. A small helper fetches the file, hoists its styles into ``, re-executes its script (so the component registers), and inserts the markup wherever you want the component to appear. Familiar to anyone arriving from Vue or Svelte. SFC Example HTML Fragment Loaded via Helper [Open Full Example ↗](https://www.wildflowerjs.com/examples/sfc/pattern-2-html-fragment.html) The `.html` fragment looks like this. ```html
``` The reusable helper, which exists because nothing in the browser will fetch and mount an HTML fragment for you. Copy it into your project once. ```javascript async function mountComponent(url, target) { const html = await fetch(url).then(r => r.text()); const wrapper = document.createElement('div'); wrapper.innerHTML = html; // Move ```javascript wildflower.component('form-arrays', { state: { contacts: [], result: '', nextId: 1 }, addContact() { this.contacts.push({ id: this.nextId++, name: '', email: '' }) }, removeContact(e, el, detail) { this.contacts.splice(detail.index, 1) }, handleSubmit(event) { event.preventDefault() this.result = JSON.stringify(this.contacts.map(c => ({ name: c.name, email: c.email }))) }, resetForm() { this.contacts = [] this.result = '' } }) ``` Live Preview ## Intrinsic Form Handling WildflowerJS provides built-in form handling with automatic synchronization, debouncing, and advanced performance optimizations: **Handled for you:** - Form data is synchronized to state before action methods are called - Built-in debouncing prevents excessive updates during typing - Automatic form validation when `data-validate` is present - No need for explicit event.preventDefault() calls - Advanced event modifiers for fine-grained control - Automatic cleanup and memory management ### Input Modifiers Add attributes to `data-model` inputs to control how values are processed: ```html
Stored: "" — length:
Stored: "" — length:
typeof: — doubled:
``` ```javascript wildflower.component('modifier-demo', { state: { raw: '', trimmed: '', price: 0 }, computed: { rawLen() { return this.raw.length }, trimLen() { return this.trimmed.length }, priceType() { return typeof this.price }, doubled() { return this.price * 2 } } }) ``` Live Preview To reduce expensive work during fast typing, debounce the action handler rather than the state update: ```html ``` ### Automatic Form Submission When a form has `data-action`, WildflowerJS automatically prevents the default submit and syncs all `data-model` fields to state before calling your method: ```html
``` ```javascript handleSubmit() { // No event.preventDefault() needed // this.email and this.message are already synced console.log('Sending:', this.email, this.message) } ``` ### Advanced Event Modifiers WildflowerJS provides additional event modifiers for complex interactions: ```html

Advanced Event Modifiers

Self-Only Container (data-event-self)

Click this container background (not the text) to trigger the action.

Clicking the button above won't trigger the container's action.

Click anywhere outside this modal to close it, or use the button below.

Last Action:

``` ### Component Definition ```javascript wildflower.component('form-modal-demo', { state: { modalOpen: false, lastAction: 'None' }, handleContainerClick() { this.lastAction = 'Container clicked (self-only)' }, handleButtonClick() { this.lastAction = 'Button inside container clicked' }, openModal() { this.modalOpen = true this.lastAction = 'Modal opened' }, closeModal() { this.modalOpen = false this.lastAction = 'Modal closed (outside click or button)' } }) ``` ### Event Modifier Reference | Modifier | Purpose | Example Use Case | | --- | --- | --- | | data-event-self | Only trigger when event target is the element itself | Prevent child element clicks from bubbling | | data-event-outside | Trigger when clicking outside the element | Close modals, dropdowns, and menus | | data-event-stop | Call event.stopPropagation() | Prevent event bubbling to parent elements | | data-event-prevent | Call event.preventDefault() | Prevent default browser behavior | | data-event-once | Event listener triggers only once | One-time initialization actions | | data-event-passive | Use passive event listener | Better performance for scroll/touch events | | data-event-capture | Use capture phase event listener | Handle events during capture phase | ## Early Submit Edge Case This is narrow but worth knowing if you build forms that depend on `event.preventDefault()` to stop a submit. Action handlers fire on click immediately, even if the component's `init()` hook hasn't completed yet. The framework [queues those calls and replays them after init](https://www.wildflowerjs.com/docs/lifecycle#actions-before-init-completes). For typical handlers this is invisible. For form submits it has one wrinkle: the captured `event` object is the original DOM event, and by the time the queued call replays, the browser has already processed the event's default action. Calling `event.preventDefault()` at that point is a no-op. In practice this affects: - A user submitting a form during the brief window between mount and `init()` completing. - Components that subscribe to slow stores (`init()` waits for store readiness, widening the window). - Tests that synchronously dispatch a submit immediately after `_scanForComponents()`. **Workaround** if your form handler must reliably prevent submission: defer the prevent into `init()` using a one-shot guard, or use `data-event-prevent` on the form element itself (the framework intercepts the submit before user-code timing matters): ```html
...
``` Most apps will never hit this; the window between mount and init is sub-frame for components without store subscriptions, and natural form submits during that window are rare. But it's worth knowing the mechanism if you ever see "form submitted even though I called preventDefault." ## Cross-Field Rules in Depth The [basic form of a rule](https://www.wildflowerjs.com/docs/forms) is a name and an expression. The object form adds three controls: ```javascript rules: { 'destination': { check: 'pickup != "" || address != ""', when: 'delivery', // an ordinary boolean state property, checked for truthiness message: 'Provide a pickup point or an address', fields: ['pickup', 'address'] // which inputs get the invalid class } } ``` | Key | Type | Required | Default | | --- | --- | --- | --- | | check | string or function | Yes | n/a | | message | string | No | the rule's name | | when | string or function | No | always in force | | fields | array of strings | No | see below | `check` and `when` accept the same two forms: a CSP-safe expression string evaluated over state and computed names, or a function bound to the component. Only `check` is required; a rule with no `when:` is always in force. #### when: gating `when:` resolves the same way `check:` does: `delivery` in the example above is a plain state property on the component, most likely a checkbox bound with `data-model="delivery"`. A rule with `when:` is checked only while its condition holds, so a delivery-address rule that applies only when that checkbox is checked needs no conditional logic in the check itself; gate it and the check stays a clean statement of the requirement. A full expression works here too, with the same operators available everywhere else in the framework: `when: 'delivery && accepted'` gates the rule on only once both are true. `when:` may also be a function, for a gate that a string expression can't express, such as checking membership in a list: ```javascript rules: { 'destination': { check: 'pickup != "" || address != ""', when() { return ['standard', 'express', 'freight'].includes(this.method); }, fields: ['pickup', 'address'] } } ``` It runs bound to the component and follows the same return-value contract as a function `check:`: the value returned IS the verdict, and a promise, `undefined`, or a string is diagnosed (WF-234) and the rule is skipped for that pass rather than guessed at. ```html
Order placed.
``` ```javascript wildflower.component('shipping-when-demo', { state: { method: 'standard', pickup: '', address: '', rush: false, acknowledgeSurcharge: false, placed: false }, rules: { // when: is a function here because a CSP-safe string can't // express an array-membership check. The check: can stay a plain // string because the inputs use data-model-trim, so a space // alone never reaches state as a "value". 'destination': { check: 'pickup != "" || address != ""', when() { return ['standard', 'express', 'freight'].includes(this.method); }, fields: ['pickup', 'address'], message: 'Provide a pickup point or an address; only pickup in store needs neither' }, // when: is a plain string here, since a single checkbox is all // the gate needs. 'surcharge': { check: 'acknowledgeSurcharge == true', when: 'rush', fields: ['acknowledgeSurcharge'], message: 'Accept the rush surcharge to place a rush order' } }, save() { this.placed = true; }, // Explicit reset for anyone who won't reach for the demo's own Reset // button in the preview header. resetForm() { this.method = 'standard'; this.pickup = ''; this.address = ''; this.rush = false; this.acknowledgeSurcharge = false; this.placed = false; }, // Changing anything after a successful submit clears the confirmation, // so you can try a different combination and see the rules run again. watch: { // A new method needs its own destination entered fresh, so a // leftover pickup point from a prior method doesn't silently // satisfy this one. method() { this.placed = false; this.pickup = ''; this.address = ''; }, pickup() { this.placed = false; }, address() { this.placed = false; }, // Turning rush off also clears its dependent checkbox, so it // doesn't come back pre-checked the next time rush is turned on. rush() { this.placed = false; if (!this.rush) this.acknowledgeSurcharge = false; }, acknowledgeSurcharge() { this.placed = false; } } }); ``` ```css .error-message { color: #dc3545; font-size: 0.85rem; min-height: 1.2em; margin-top: 0.25rem; } .form-control.invalid, .form-select.invalid { border-color: #dc3545; background: #fff5f5; } ``` Live Preview #### fields: attribution Without `fields:`, a **string** rule adds the `invalid` class to every `data-model` input whose state variable the check reads. Declare `fields:` when the check reads more than it should flag. An either-or rule reads both fields but you may want only one highlighted, or both; that choice is yours, per rule. A **function** check has no expression for the framework to read, so this inference doesn't apply to it: without `fields:`, a failing function check still blocks submit and still writes its message to a `data-error-for` matching the rule's name, but no input gets the `invalid` class. Declare `fields:` on any function check that should highlight specific inputs. ```html

Budget: $500

Order placed.
``` ```javascript wildflower.component('fields-demo', { state: { qty: 0, price: 0, placed: false }, rules: { // String check, no fields: given, so it auto-marks "qty", the // only data-model input the expression reads. 'Quantity must be positive': 'qty > 0', // Function check, no fields: given, so nothing gets the invalid // class, even though this still blocks. 'budget': { check() { return (this.qty * this.price) <= 500; }, message: 'Total exceeds the $500 budget' } }, save() { this.placed = true; }, // Explicit reset for anyone who won't reach for the demo's own Reset // button in the preview header. resetForm() { this.qty = 0; this.price = 0; this.placed = false; }, // Changing anything after a successful submit clears the confirmation, // so you can try a different combination and see the rules run again. watch: { qty() { this.placed = false; }, price() { this.placed = false; } } }); ``` ```css .error-message { color: #dc3545; font-size: 0.85rem; min-height: 1.2em; margin-top: 0.25rem; } .form-control.invalid, .form-select.invalid { border-color: #dc3545; background: #fff5f5; } ``` Live Preview #### Function checks A check may be a function instead of an expression string. It runs bound to the component context, so state, computed properties, and methods are all reachable: ```javascript rules: { 'Quantity fits remaining stock': { check() { return Number(this.qty) <= this.remainingStock; }, fields: ['qty'] } } ``` A function check that throws does not silently pass or fail the form. The rule is skipped for that pass, the other rules and per-input validation still run, and the dev build reports the rule by name with the error, once (WF-229). #### Computed properties in rules String checks may reference computed names alongside state. A rule like `'total Rules run at the form boundary, where the user can repair the problem before anything submits. Checks a user cannot act on, like internal consistency assumptions, do not belong here, since blocking a submit on one leaves no way forward. Keep the validation surface to conditions a person can fix. ## Form Best Practices ##### Do - Use data-model for two-way binding - Use simple data-action="methodName" on forms - Leverage built-in debouncing with data-event-debounce on action handlers - Add data-validate for automatic validation - Use appropriate input types with validation attributes - Trust framework's intrinsic form handling ##### Don't - Use overcomplicated data-action="submit:method" syntax - Manually call event.preventDefault() in form actions - Validate on every keystroke without debouncing - Show errors before user finishes typing - Forget to sanitize form data before submission - Use generic error messages --- # Expressions > Source: https://www.wildflowerjs.com/docs/expressions WildflowerJS binding attributes accept both simple property names and inline JavaScript expressions, enabling dynamic values without computed properties. ## Overview Most binding attributes accept either a **simple property name** or a **JavaScript expression**. Simple property names resolve directly from component state or computed properties. Expressions are evaluated at render time and re-evaluated whenever their dependencies change. ```html ``` The framework detects whether a binding value is a property path or an expression. A value is an expression when it contains an operator, parentheses, a ternary, `??` or `?.`, a keyword operator such as `typeof`, or a bracket with anything but a number in it, as in `items[index]`. In the default mode an expression can call a method on a value, such as `data-bind="price.toFixed(2)"` or `data-show="form.isDirty()"`, and it updates when the state the method reads changes. The component's own methods are not in a binding's scope, and a computed's name already stands for its value, so `data-bind="formatTotal()"` and `data-bind="total()"` render nothing; declare a computed and bind its name. Development builds warn about both ([WF-522](https://www.wildflowerjs.com/docs/error-codes?code=WF-522)). CSP mode allows no calls but `external()`; see CSP Mode Limitations. ## Where Expressions Work Expressions are supported in these binding attributes: | Attribute | Example | Purpose | | --- | --- | --- | | data-bind | data-bind="price * qty" | Text content | | data-bind-html | data-bind-html="htmlContent" | HTML content | | data-bind-class | data-bind-class="isActive ? 'on' : 'off'" | CSS classes | | data-bind-style | data-bind-style="{ color: isError ? 'red' : 'black' }" | Inline styles | | data-bind-attr | data-bind-attr="{ disabled: !isValid }" | HTML attributes | | data-show | data-show="items.length > 0" | Visibility toggle | | data-render | data-render="isLoggedIn && hasPermission" | Conditional rendering | ## Syntax Reference ### Property References Reference state properties and computed properties by name. Nested properties use dot notation: ```html ``` ### Arithmetic ```html ``` Exponentiation follows JavaScript's rules: it binds tighter than multiplication and chains right to left, so `2 ** 3 ** 2` is 512. ### Comparisons ```html
Has items
Active
High score
Visible
``` ### Logical Operators ```html
Admin Panel
Status
``` ### Ternary Operator ```html ``` ### Negation ```html
Visible
Ready
``` ### String and Number Literals ```html ``` ### Store Access Access store values in expressions using the `$storeName.property` shorthand: ```html
Items in cart
``` The `$store.path` syntax is converted to `external('store', 'path')` internally. See [Basic Stores](https://www.wildflowerjs.com/docs/basic-stores) for more on store subscriptions. ## Expressions vs Computed Properties Both inline expressions and computed properties can derive values from state. Choose based on complexity: | Use | When | | --- | --- | | Inline expression | Simple, one-off calculations: a comparison, a ternary, basic arithmetic | | Computed property | Complex logic, reused across multiple bindings, or multi-step calculations | ```html ``` ```javascript wildflower.component('invoice', { state: { price: 29.99, quantity: 3, taxRate: 0.08 }, computed: { formattedTotal() { var total = this.price * this.quantity var tax = total * this.taxRate return '$' + (total + tax).toFixed(2) }, statusClass() { if (this.quantity === 0) return 'text-muted' if (this.quantity > 10) return 'text-success fw-bold' return 'text-primary' } } }) ``` As a rule of thumb: if the expression needs more than one operator or is used in multiple places, extract it into a computed property. ## Content Security Policy (CSP) By default, WildflowerJS compiles expressions with `new Function()`. In environments with strict [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) headers that block `unsafe-eval`, the framework detects this and switches to a built-in parser that never calls `new Function()`. Auto-detection works by attempting one `new Function()` call at startup; under a strict policy that attempt is blocked and reported as a single benign `securitypolicyviolation` before the framework switches. **CSP mode is not the slow mode.** The parser compiles each expression once into a tree of closures, with identifiers resolved to argument positions at compile time, so evaluating one indexes an array rather than walking a syntax tree. Per-call overhead against `new Function()` is under 3x on a sub-nanosecond baseline, which is why the submitted [js-framework-benchmark](https://krausest.github.io/js-framework-benchmark/2026/chrome158.html) entries run in this mode and post the results they do. What the default buys is not speed, it is the wider grammar described under CSP Mode Limitations below. ### Expressions are code, and markup is where they live A binding attribute is evaluated as JavaScript, so `data-bind` deserves the same trust you give a ` ``` This matters on sites that use `report-uri` or `report-to`: without the attribute, the startup capability probe files one violation report per page load with your security tooling. [See it live](https://www.wildflowerjs.com/examples/csp-strict/): an interactive list running under `default-src 'none'` with a violation counter reading zero. ### Runtime switch: wildflower.config() When the script tag isn't under your control, switch at runtime instead: ```javascript wildflower.config({ forceCSPMode: true }); ``` Expressions compiled after the call use the CSP-safe parser. This runs after the framework has already loaded, so it cannot suppress the startup probe; prefer the attribute when you control the script tag. ### What CSP Mode Supports The AST-based parser supports the same expression syntax used in bindings: - **Arithmetic:** `+`, `-`, `*`, `/`, `%`, `**` - **Comparison:** `==`, `!=`, `===`, `!==`, `<`, `>`, `<=`, `>=` - **Logical:** `&&`, `||`, `!` - **Bitwise:** `&`, `|`, `^`, `~`, `<<`, `>>`, `>>>` - **Ternary:** `condition ? a : b` - **Unary:** `-x`, `+x`, `!x`, `~x` - **Property access:** dot notation (`user.name`) and bracket notation (`items[0]`) - **Function calls:** `external()` for store access - **Literals:** strings, numbers, `true`, `false`, `null`, `undefined`, arrays - **Grouping:** parentheses `(a + b) * c` ### CSP Mode Limitations The AST parser does **not** support: - Method calls (e.g., `str.toUpperCase()`); use a computed property instead - Arrow functions - Template literals (``hello ${name}``) - Destructuring or spread operators - Global objects (`Math`, `Date`, etc.); use computed properties for these **Note:** In standard mode expressions are compiled with `new Function()` and can reach JavaScript globals such as `Math.round()` or `Date.now()`. These do not work in CSP mode, which is the point of it: the same reachability that gives you `Math` gives an injected expression everything else on the page. Use computed properties for logic that needs global objects or method calls, and they will work in either mode. ### Security The CSP expression evaluator includes built-in security protections: - **No global access:** `window`, `document`, `fetch`, `eval`, and other browser globals are blocked - **No prototype pollution:** Access to `__proto__`, `constructor`, and `prototype` is blocked - **Scope-limited:** Expressions can only reference component state, computed properties, and store data via `external()` **Performance:** CSP-safe evaluation parses each expression once and compiles it, so the cost is paid at compile time rather than per evaluation. The remaining per-call difference is under 3x on a sub-nanosecond baseline, which does not register against the DOM work around it. Choose between the two modes on grammar and on trust, not on speed. ====================================================================== # SECTION: Lists ====================================================================== --- # Templating > Source: https://www.wildflowerjs.com/docs/templates WildflowerJS uses standard HTML `