# Templates

The core template mechanic in Symbiote.js is native browser HTML-string parsing via standard DOM API methods. This is the fastest way to create a component template instance in the object model representation.

## Runtime-agnostic by design

Symbiote.js templates are runtime and context agnostic. This applies to all template sources: strings produced by the `html` helper, plain HTML strings, external template modules, and `<template>` elements selected with `use-template`.

Templates do not execute inside a component instance and do not close over `this`. They describe markup and named bindings only; the actual component instance and data context are resolved later, when the template is rendered or hydrated.

This is an important difference from many component libraries where the template is also an instance-bound render function. In Symbiote.js, representation can stay separate from component logic, which makes templates reusable, replaceable, SSR-friendly, and easy to define outside JavaScript classes:
```js
// Universal for browser or Node.js environment:
export const cardTemplate = html`
  <h2>{{title}}</h2>
  <button ${{onclick: 'onSelect'}}>Select</button>
`;
```

For typing details, see [TypeScript](./typescript.md).

## `html` helper

The `html` tag function constructs templates using compact binding-maps:
```js
import { html } from '@symbiotejs/symbiote';

const myTemplate = html`
  <button ${{onclick: 'onBtnClick'}}>Click me!</button>
`;
```
In this example, we created the button and connected it to a `onBtnClick` handler, which should be defined in the component state.

Every binding-map is a simple JavaScript object that describes connections between the element's own properties and the component's data. It is standard JavaScript template literal syntax with no special additions.

### Dual-mode interpolation

The `html` function supports two interpolation modes:

- **Object** → converted to `bind="prop:key;"` attribute (reactive binding)
- **String / number** → concatenated as-is (native interpolation, useful for SSR page shells)

Example:
```js
const btnText = 'Click me!';
const myTemplate = html`
  <button ${{onclick: 'onBtnClick'}}>${btnText}</button>
`;
```

This dual-mode design means `html` works for both component templates and full-page SSR output — no separate "server-only template" function is needed.

### Self-closing custom elements

In standard HTML, self-closing syntax is only meaningful for void elements. Custom elements should normally be written with explicit closing tags:
```js
html`<my-component></my-component>`;
```

For convenience, the `html` helper expands empty custom element tags that use self-closing syntax:
```js
html`<my-component />`;
html`<my-component/>`;
// Both output: '<my-component></my-component>'
```

This normalization only applies to hyphenated custom element names. Native void elements keep their original form, and an existing closing tag is not duplicated:
```js
html`<input />`; // '<input />'
html`<my-component/></my-component>`; // '<my-component></my-component>'
```

## Binding to text nodes

```js
import Symbiote, { html } from '@symbiotejs/symbiote';

class MyComponent extends Symbiote {
  name = 'John';
  btnTxt = 'Click me!';
  onBtnClick() {
    console.log('Button clicked!');
  }
}

MyComponent.template = html`
  <h1>Hello {{name}}!</h1>
  <button ${{onclick: 'onBtnClick'}}>{{btnTxt}}</button>
`;
```
Text node bindings use double braces syntax — `{{myProp}}`. For each text node binding, its own text node (`Text()`) will be created.

> [!IMPORTANT]
> **SSR / ISO limitation:** `{{prop}}` bindings work by splitting DOM text nodes at runtime — they produce **no HTML attributes** in SSR output. This means the server renders the initial value correctly, but the client hydration pass has no marker to re-attach the binding. For hydratable text, use `${{textContent: 'prop'}}` instead. Enable `devMode` to get a warning when this occurs.

More about standard [Text Nodes](https://developer.mozilla.org/en-US/docs/Web/API/Text).

## Binding to template element's own properties

```js
MyComponent.template = html`
  <button ${{onclick: 'handlerName'}}>Click</button>
`;
```
The `${{key: 'value'}}` interpolation creates a `bind="key:value;"` attribute. Keys are DOM element property names; values are component reactive state property names (as strings).

### Class property fallback (3.x)

For any binding key not found in `init$`, Symbiote falls back to a **class property** (own instance property) with the same name. Functions are automatically bound to the component instance:
```js
class MyComp extends Symbiote {
  // Approach 1: state property in init$
  init$ = { count: 0 };

  // Approach 2: class property (fallback)
  label = 'Click me';
  onSubmit() { console.log('submitted'); }
}

MyComp.template = html`
  <label>{{label}}</label>
  <button ${{onclick: 'onSubmit'}}>{{count}}</button>
`;
```

> Value properties are checked via `Object.hasOwn`, so inherited `HTMLElement` properties like `title`, `hidden`, etc. are never picked up. Prototype methods are also resolved as fallback handlers.

> [!TIP]
> Use class property fallback for **simple components** — it keeps the code compact and readable.  For **complex components** with many reactive properties, prefer `init$` to explicitly separate reactive state from regular class properties.

## Binding to element's nested properties

Symbiote.js allows binding to nested properties of template elements:
```js
MyComponent.template = html`
  <div ${{'style.color': 'myCssValue'}}>Some text...</div>
`;
```

You can also bind to a nested component's reactive state directly, using the `$` proxy key:
```js
MyComponent.template = html`
  <my-component ${{'$.nestedPropName': 'propName'}}></my-component>
`;
```

## Binding an object to child state

Bind to `$` to merge an object from the parent context into a child component's reactive state:

```js
import Symbiote, { html } from '@symbiotejs/symbiote';

class ProfileCard extends Symbiote {
  init$ = { name: '', role: 'Reader' };
}
ProfileCard.template = html`
  <strong ${{textContent: 'name'}}></strong>
  <span ${{textContent: 'role'}}></span>
`;
ProfileCard.reg('profile-card');

class ProfilePanel extends Symbiote {
  init$ = { profile: { name: 'Alex' } };
}
ProfilePanel.template = html`
  <profile-card ${{$: 'profile'}}></profile-card>
`;
ProfilePanel.reg('profile-panel');
```

The equivalent plain HTML binding is `<profile-card bind="$: profile"></profile-card>`. Register the child class before mounting the parent. Symbiote defers the initial assignment until the child initializes, so it displays `Alex` with its default role `Reader`.

After mounting, `panel.$.profile = { role: 'Editor' }` updates the child's role and preserves its name. New keys are registered, and the child's `$` proxy remains the same object. Child changes do not publish back to the parent. Object mutations alone do not notify; publish the parent property again or call `panel.notify('profile')`. See [state merging](./properties.md#merging-state) for notification and context rules.

## Binding to HTML attributes

To bind a property to an element's attribute, use the `@` prefix:
```js
MyComponent.template = html`
  <div ${{'@hidden': 'isHidden'}}></div>
  <input ${{'@disabled': 'isDisabled'}}>
  <div ${{'@data-value': 'myValue'}}></div>
`;
```
The `@` prefix means "bind to HTML attribute" (not DOM property). For boolean attributes: `true` → attribute present, `false` → attribute removed.

> `@` is for binding syntax only — do NOT use it as a regular HTML attribute prefix (`<div ${{'@hidden': 'isHidden'}}></div>` will be rendered as `<div hidden></div>` if `isHidden` is `true`, and as `<div></div>` if `isHidden` is `false`).

## Type casting

You can cast any property value to `boolean` using `!`:

Inversion:
```js
html`<div ${{'@hidden': '!showContent'}}> ... </div>`;
```

Double inversion is supported:
```js
html`<div ${{'@contenteditable': '!!hasText'}}> ... </div>`;
```

## Property tokens (key prefixes)

| Prefix | Meaning | Example |
|--------|---------|---------|
| _(none)_ | Local state | `{{count}}` |
| `^` | Pop-up | `{{^parentProp}}` |
| `*` | Shared context | `{{*sharedProp}}` |
| `/` | Named context | `{{APP/myProp}}` |
| `--` | CSS Data | `{{--my-css-var}}` |
| `+` | Computed | `'+sum': () => ...` |

> The `^` prefix resolves properties registered in the parent's data context (`init$` or `add$()`). Class property fallbacks are **not** checked during the parent walk.

> More details in the [Context](./context.md) section.

## Loose-coupling alternative

Templates can be written as plain HTML without any JavaScript context:
```html
<div bind="textContent: myProp"></div>
<div bind="onclick: handler; @hidden: !flag"></div>
```

## Shadow DOM slots

> [Slots](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot) allow you to define placeholders in your template that can be filled with external markup.

Shadow DOM slots work out of the box, as expected by standard. No additional processors needed. To enable Shadow DOM, set the `renderShadow` flag in your component or define shadow styles:
```js
class MyComponent extends Symbiote {
  renderShadow = true;
}

// Or just define shadow styles:
MyComponent.shadowStyles = css`
  :host {
    display: block;
  }
`;

// Then you can use standard Shadow DOM slots:
MyComponent.template = html`
  <slot></slot>
`;
```

## Light DOM Slots (Symbiote.js feature, non-standard)

Since version 2.x, light DOM slot processing must be imported and added explicitly:
```js
import { slotProcessor } from '@symbiotejs/symbiote/core/slotProcessor.js';

class MyWrapper extends Symbiote {
  constructor() {
    super();
    this.templateProcessors.add(slotProcessor);
  }
}

MyWrapper.template = html`
  <header><slot name="header"></slot></header>
  <main><slot></slot></main>
`;
```

Usage:
```html
<my-wrapper>
  <h1 slot="header">Title</h1>
  <p>Default slot content</p>
</my-wrapper>
```

## Element references

Use the `ref` attribute to get element references in your code:
```js
html`
  <div>
    <input ref="nameInput">
    <button ref="submitBtn" ${{onclick: 'onSubmit'}}>Submit</button>
  </div>
`;
```

Reference names should be unique. Access them via `this.ref`:
```js
class MyComponent extends Symbiote {
  renderCallback() {
    this.ref.nameInput.focus();
    this.ref.submitBtn.disabled = true;
  }
}
```

## Dynamic list rendering

To render efficient dynamic reactive lists, use the `itemize` API:
```js
class MyComponent extends Symbiote {
  listData = [
    { firstName: 'John', secondName: 'Snow' },
    { firstName: 'Jane', secondName: 'Stone' },
  ];
}

MyComponent.template = html`
  <h1>My list:</h1>
  <ul itemize="listData">
    <template>
      <li>{{firstName}} - {{secondName}}</li>
    </template>
  </ul>
`;
```

> More information about `itemize` API in the [List Rendering](./list-rendering.md) section.

## External customizable templates

Symbiote.js allows components to connect templates defined elsewhere in the HTML document.

Set the `allowCustomTemplate` flag:
```js
class MyComponent extends Symbiote {
  allowCustomTemplate = true;
}
```

Define templates somewhere in HTML markup:
```html
<template id="first">
  <h1>{{headingText}}</h1>
</template>

<template id="second">
  <h2>{{headingText}}!</h2>
</template>
```

Use them:
```html
<my-component use-template="#first"></my-component>
<my-component use-template="#second"></my-component>
```

---

Next: [Properties →](./properties.md)
