On This Page
Template
The Template class represents a compiled template and provides methods for manipulating and rendering it. It integrates with the Semantic UI component system and supports various rendering engines.
Semantic UI ships with a native rendering engine by default, which renders templates directly to DOM. An optional Lit engine compiles templates to lit html and is available when imported and registered explicitly.
Advanced Use Only When using Semantic UI components, a template will automatically be created from
defineComponent. It is not recommended to useTemplateclass on its own except for advanced use-cases.
Constructor
Syntax
new Template(options)Parameters
| Name | Type | Description |
|---|---|---|
| options | Object | Configuration options for the template |
Options
| Name | Type | Description |
|---|---|---|
| templateName | string | Name of the template |
| ast | Object[] | Compiled AST of the template |
| template | string | The template string |
| data | Object | Initial data for the template |
| element | Element | The DOM element associated with the template |
| renderRoot | Element | The root element for rendering |
| css | string | CSS styles associated with the template |
| events | Object | Event handlers for the template |
| keys | Object | Key bindings for the template |
| defaultState | Object | Configuration for reactive state |
| subTemplates | Object | Sub-templates used within this template |
| createComponent | Function | Function to create the component instance |
| parentTemplate | Template | The parent template when nested |
| renderingEngine | string | The rendering engine to use (default: ‘native’) |
| isPrototype | boolean | Whether this is a prototype template |
| attachStyles | boolean | Whether to attach styles to the renderRoot |
| onCreated | Function | Callback when the template is created |
| onRendered | Function | Callback when the template is rendered |
| onDestroyed | Function | Callback when the template is destroyed |
| onThemeChanged | Function | Callback when the theme changes |
Usage Examples
Basic Initialization with Template String
import { Template } from '@semantic-ui/templating';
const template = new Template({ templateName: 'greet-user', template: 'Welcome <b>{name}</b>', data: { name: 'John' }});Initialization with AST
import { TemplateCompiler } from '@semantic-ui/compiler';import { Template } from '@semantic-ui/templating';
const compiler = new TemplateCompiler('Welcome <b>{name}</b>');const ast = compiler.compile();
const template = new Template({ templateName: 'greet-user', ast, data: { name: 'John' }});Advanced Initialization
import { Template } from '@semantic-ui/templating';
const template = new Template({ templateName: 'user-profile', template: ` <div class="user-profile"> <h1>{user.name}</h1> <p>{user.email}</p> <button class="update">Update</button> </div> `, data: { user: { name: 'John Doe', email: 'john@example.com' } }, events: { 'click .update': ({ self }) => self.updateUser() }, defaultState: { user: { name: 'John Doe', email: 'john@example.com' } }, createComponent: ({ state }) => ({ updateUser() { state.user.set({ name: 'Jane Doe', email: 'jane@example.com' }); } }), onRendered: () => console.log('User profile rendered'), attachStyles: true, css: ` .user-profile { padding: 20px; border: 1px solid #ccc; } `});Methods
initialize
Initializes the template, setting up reactive state and event handlers.
Syntax
template.initialize()Usage
import { Template } from '@semantic-ui/templating';
const template = new Template({ templateName: 'greet-user', template: 'Welcome <b>{name}</b>', data: { name: 'John' }});
template.initialize();mount
Mounts the template into a DOM element or shadow root. Calling mount on a prototype template clones an instance and mounts the clone. A plain element is upgraded with the component class while mounted so el.settings, property accessors, el.$(), and el.unmount() work directly on the element.
Syntax
template.mount(target, options);Parameters
| Name | Type | Description |
|---|---|---|
| target | Element | ShadowRoot | Target element or shadow root (upgraded in place, or treated as a container when anchor is passed) |
| options | Object | Optional mount configuration |
Options
| Name | Type | Description |
|---|---|---|
| settings | Object | Initial settings merged over declared defaults |
| data | Object | Data for the template beyond its declared settings |
| anchor | Node | null | Mounts the template as a range before anchor inside target, null to append. target is not upgraded and keeps its own children |
| signal | AbortSignal | Unmounts the template automatically when the signal aborts |
Returns
Template - The mounted template instance.
Usage
import { defineComponent } from '@semantic-ui/component';
const UserCard = defineComponent({ template: '<div class="card">{name}</div>', defaultSettings: { name: 'Anonymous' },});
const el = document.querySelector('#card');const card = UserCard.mount(el, { settings: { name: 'Ada' },});
el.name = 'Grace';Mounting at an anchor
When anchor is passed, target is treated as a container and keeps its existing children. The template renders as a DOM range before anchor (or at the end of target when anchor is null), matching insertBefore. Because target is not upgraded, multiple templates can mount inside the same container alongside static markup. Inside the mounted template, el is the container and findParent() resolves the enclosing component if present (note that custom elements rendered inside the range walk the DOM past the unupgraded container to that enclosing component, not the range template).
const main = document.querySelector('main');const marker = main.querySelector('.outlet');
const page = About.mount(main, { anchor: marker, data: { route: '/about' } });// <main> <nav>…</nav> [about's nodes] .outlet <footer>…</footer> </main>
page.update({ route: '/about/team' });page.unmount(); // removes exactly the nodes it placed, the marker survivesComponents with a tagName cannot be mounted at an anchor — create the custom element and insert it before anchor directly.
unmount
Tears down a mounted template, fires onDestroyed, clears the rendered nodes from target, and restores target’s prototype and properties if it was upgraded in light DOM. A range mount removes only its own nodes.
Syntax
template.unmount();Usage
const card = UserCard.mount(el, { settings: { name: 'Ada' },});
card.unmount();render
Brings the template to the data it is given and builds it once. A later call updates in place and returns what the engine produced the first time.
Syntax
template.render(data)Parameters
| Name | Type | Description |
|---|---|---|
| data | Object | Keys to merge before building |
Returns
The rendered template content. The shape depends on the rendering engine — DOM nodes for native, a TemplateResult for lit.
Usage
import { Template } from '@semantic-ui/templating';
const template = new Template({ templateName: 'greet-user', template: 'Welcome <b>{name}</b>', data: { name: 'John' }});
document.body.append(template.render({ title: 'Hello' }));update
Brings the template to the data it is given. A declared setting moves through its signal. Every other key is plain data, re-evaluated wherever the template reads it, including inside {#rerender} blocks and subtemplate props.
Syntax
template.update(data)Parameters
| Name | Type | Description |
|---|---|---|
| data | Object | Keys to merge |
Returns
boolean - Whether a plain key changed.
Usage
import { Template } from '@semantic-ui/templating';
const template = new Template({ templateName: 'greet-user', template: 'Welcome <b>{name}</b>', data: { name: 'John' }});
document.body.append(template.render());template.update({ name: 'Jane' });rerender
Re-evaluates every expression in place and rebuilds every {#rerender} block. The escape valve for content that reads something outside the reactive graph.
Syntax
template.rerender()setDataContext
Merges data into the template’s context without touching the rendered output. update calls this, then re-evaluates what changed.
Syntax
template.setDataContext(data)Parameters
| Name | Type | Description |
|---|---|---|
| data | Object | Keys to merge |
Returns
boolean - Whether a key with nothing reactive behind it changed.
clone
Creates a new Template instance from a prototype. Each clone has its own data, element, and DOM bindings; AST, CSS, and callbacks are shared with the prototype by reference.
Syntax
template.clone(settings)Parameters
| Name | Type | Description |
|---|---|---|
| settings | Object | Per-instance overrides like data, element, parentTemplate |
Returns
Template - A new Template instance derived from this prototype.
Usage
import { Template } from '@semantic-ui/templating';
const prototype = new Template({ templateName: 'greet-user', template: 'Welcome <b>{name}</b>', isPrototype: true,});
const instance = prototype.clone({ data: { name: 'Jane' } });attachEvents
Attaches event handlers to the rendered template.
Syntax
template.attachEvents(events)Parameters
| Name | Type | Description |
|---|---|---|
| events | Object | Event handlers to attach |
Usage
import { Template } from '@semantic-ui/templating';
const template = new Template({ templateName: 'greet-user', template: 'Welcome <b>{name}</b> <button class="greet">Greet</button>', data: { name: 'John' }});
template.attachEvents({ 'click .greet': () => console.log('Greeting button clicked')});Lifecycle Hooks
The Template class provides several lifecycle hooks that can be overridden to add custom behavior:
onCreatedonRenderedonDestroyedonThemeChanged
Usage
import { Template } from '@semantic-ui/templating';
const template = new Template({ templateName: 'greet-user', template: 'Welcome <b>{name}</b>', data: { name: 'John' }});
template.onCreated = () => console.log('Template created');template.onRendered = () => console.log('Template rendered');template.onDestroyed = () => console.log('Template destroyed');template.onThemeChanged = () => console.log('Theme changed');