# Template

class

A basic Template class. It renders a DOM HTML element or text from a [definition](module_ui_template-TemplateDefinition.md) and supports element attributes, children, bindings to [observables](module_utils_observablemixin-Observable.md) and DOM event propagation.

A simple template can look like this:

```typescript
const bind = Template.bind( observable, emitter );

new Template( {
	tag: 'p',
	attributes: {
		class: 'foo',
		style: {
			backgroundColor: 'yellow'
		}
	},
	on: {
		click: bind.to( 'clicked' )
	},
	children: [
		'A paragraph.'
	]
} ).render();
```

and it will render the following HTML element:

```html
<p class="foo" style="background-color: yellow;">A paragraph.</p>
```

Additionally, the `observable` will always fire `clicked` upon clicking `<p>` in the DOM.

See [`TemplateDefinition`](module_ui_template-TemplateDefinition.md) to know more about templates and complex template definitions.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L69)

<a id="properties">

## Properties

<a id="member-attributes">

### `attributes?: Record<string, AttributeValues>`

The attributes of the template, e.g. `{ id: [ 'ck-id' ] }`, corresponding with the attributes of an HTML element.

**Note**: This property only makes sense when [`tag`](#member-tag) is defined.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L89)

<a id="member-children">

### `children?: Array<Node | View<HTMLElement> | Template | ViewCollection<View<HTMLElement>>>`

The children of the template. They can be either:

* independent instances of [`Template`](module_ui_template-Template.md) (sub–templates),
* native DOM Nodes.

**Note**: This property only makes sense when [`tag`](#member-tag) is defined.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L98)

<a id="member-eventListeners">

### `eventListeners?: Record<string, Array<TemplateToBinding>>`

The DOM event listeners of the template.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L103)

<a id="member-ns">

### `ns?: string`

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L70)

<a id="member-tag">

### `tag?: string`

The tag (`tagName`) of this template, e.g. `div`. It also indicates that the template renders to an HTML element.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L76)

<a id="member-text">

### `text?: Array<TemplateSimpleValue | TemplateBinding>`

The text of the template. It also indicates that the template renders to a DOM text node.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L81)

<a id="member-_isRendered">

### `_isRendered: boolean` _(private)_

Indicates whether this particular Template instance has been [rendered](#function-render).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L109)

<a id="member-_revertData">

### `_revertData: RevertData | null` _(private)_

The data used by the [`revert`](#function-revert) method to restore a node to its original state.

See: [`apply`](#function-apply).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L116)

<a id="methods">

## Methods

<a id="function-constructor">

### `constructor( def )`

Creates an instance of the [`Template`](module_ui_template-Template.md) class.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L123)

#### Parameters

* `def: TemplateDefinition`

  The definition of the template.

<a id="function-apply">

### `apply( node ) → HTMLElement | Text`

Applies the template to an existing DOM Node, either HTML element or text.

**Note:** No new DOM nodes will be created. Applying extends:

[attributes](module_ui_template-TemplateDefinition.md), [event listeners](module_ui_template-TemplateDefinition.md), and `textContent` of [children](module_ui_template-TemplateDefinition.md) only.

**Note:** Existing `class` and `style` attributes are extended when a template is applied to an HTML element, while other attributes and `textContent` are overridden.

**Note:** The process of applying a template can be easily reverted using the [`revert`](#function-revert) method.

```typescript
const element = document.createElement( 'div' );
const observable = new Model( { divClass: 'my-div' } );
const emitter = Object.create( EmitterMixin );
const bind = Template.bind( observable, emitter );

new Template( {
	attributes: {
		id: 'first-div',
		class: bind.to( 'divClass' )
	},
	on: {
		click: bind( 'elementClicked' ) // Will be fired by the observable.
	},
	children: [
		'Div text.'
	]
} ).apply( element );

console.log( element.outerHTML ); // -> '<div id="first-div" class="my-div"></div>'
```

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L192)

#### Parameters

* `node: HTMLElement | Text`

  Root node for the template to apply.

#### Returns

* `HTMLElement | Text`

#### Related:

* [Template#render](#function-render)
* [Template#revert](#function-revert)

<a id="function-delegate">

### `delegate( events ) → EmitterMixinDelegateChain` _(inherited)_

Delegates selected events to another [`Emitter`](module_utils_emittermixin-Emitter.md). For instance:

```typescript
emitterA.delegate( 'eventX' ).to( emitterB );
emitterA.delegate( 'eventX', 'eventY' ).to( emitterC );
```

then `eventX` is delegated (fired by) `emitterB` and `emitterC` along with `data`:

```typescript
emitterA.fire( 'eventX', data );
```

and `eventY` is delegated (fired by) `emitterC` along with `data`:

```typescript
emitterA.fire( 'eventY', data );
```

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L539)

#### Parameters

* `events: Array<string>`

  Event names that will be delegated to another emitter.

#### Returns

* `EmitterMixinDelegateChain`

<a id="function-fire">

### `fire( eventOrInfo, args ) → GetEventInfo<TEvent>[ 'return' ]` _(inherited)_

Fires an event, executing all callbacks registered for it.

The first parameter passed to callbacks is an [`EventInfo`](module_utils_eventinfo-EventInfo.md) object, followed by the optional `args` provided in the `fire()` method call.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L512)

#### Type parameters

* `TEvent: extends BaseEvent`

  The type describing the event. See [`BaseEvent`](module_utils_emittermixin-BaseEvent.md).

#### Parameters

* `eventOrInfo: GetNameOrEventInfo<TEvent>`

  The name of the event or `EventInfo` object if event is delegated.

* `args: TEvent[ 'args' ]`

  Additional arguments to be passed to the callbacks.

#### Returns

* `GetEventInfo<TEvent>[ 'return' ]`

  By default the method returns `undefined`. However, the return value can be changed by listeners through modification of the [`evt.return`](module_utils_eventinfo-EventInfo.md#member-return)'s property (the event info is the first param of every callback).

<a id="function-getViews">

### `getViews() → IterableIterator<View<HTMLElement>>`

Returns an iterator which traverses the template in search of [`View`](module_ui_view-View.md) instances and returns them one by one.

```typescript
const viewFoo = new View();
const viewBar = new View();
const viewBaz = new View();
const template = new Template( {
	tag: 'div',
	children: [
		viewFoo,
		{
			tag: 'div',
			children: [
				viewBar
			]
		},
		viewBaz
	]
} );

// Logs: viewFoo, viewBar, viewBaz
for ( const view of template.getViews() ) {
	console.log( view );
}
```

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L255)

#### Returns

* `IterableIterator<View<HTMLElement>>`

<a id="function-listenTo:BASE_EMITTER">

### `listenTo( emitter, event, callback, options? ) → void` _(inherited)_

Registers a callback function to be executed when an event is fired in a specific (emitter) object.

Events can be grouped in namespaces using `:`. When namespaced event is fired, it additionally fires all callbacks for that namespace.

```typescript
// myEmitter.on( ... ) is a shorthand for myEmitter.listenTo( myEmitter, ... ).
myEmitter.on( 'myGroup', genericCallback );
myEmitter.on( 'myGroup:myEvent', specificCallback );

// genericCallback is fired.
myEmitter.fire( 'myGroup' );
// both genericCallback and specificCallback are fired.
myEmitter.fire( 'myGroup:myEvent' );
// genericCallback is fired even though there are no callbacks for "foo".
myEmitter.fire( 'myGroup:foo' );
```

An event callback can [stop the event](module_utils_eventinfo-EventInfo.md#member-stop) and set the [return value](module_utils_eventinfo-EventInfo.md#member-return) of the [`fire`](#function-fire) method.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L475)

#### Type parameters

* `TEvent: extends BaseEvent`

  The type describing the event. See [`BaseEvent`](module_utils_emittermixin-BaseEvent.md).

#### Parameters

* `emitter: Emitter`

  The object that fires the event.

* `event: TEvent[ 'name' ]`

  The name of the event.

* `callback: GetCallback<TEvent>`

  The function to be called on event.

* `options?: GetCallbackOptions<TEvent>`

  Additional options.

#### Returns

* `void`

<a id="function-off">

### `off( event, callback ) → void` _(inherited)_

Stops executing the callback on the given event. Shorthand for [`this.stopListening( this, event, callback )`](#function-stopListening:BASE_STOP).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L444)

#### Parameters

* `event: string`

  The name of the event.

* `callback: Function`

  The function to stop being called.

#### Returns

* `void`

<a id="function-on">

### `on( event, callback, options? ) → void` _(inherited)_

Registers a callback function to be executed when an event is fired.

Shorthand for [`this.listenTo( this, event, callback, options )`](#function-listenTo:BASE_EMITTER) (it makes the emitter listen on itself).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L416)

#### Type parameters

* `TEvent: extends BaseEvent`

  The type descibing the event. See [`BaseEvent`](module_utils_emittermixin-BaseEvent.md).

#### Parameters

* `event: TEvent[ 'name' ]`

  The name of the event.

* `callback: GetCallback<TEvent>`

  The function to be called on event.

* `options?: GetCallbackOptions<TEvent>`

  Additional options.

#### Returns

* `void`

<a id="function-once">

### `once( event, callback, options? ) → void` _(inherited)_

Registers a callback function to be executed on the next time the event is fired only. This is similar to calling [`on`](#function-on) followed by [`off`](#function-off) in the callback.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L431)

#### Type parameters

* `TEvent: extends BaseEvent`

  The type descibing the event. See [`BaseEvent`](module_utils_emittermixin-BaseEvent.md).

#### Parameters

* `event: TEvent[ 'name' ]`

  The name of the event.

* `callback: GetCallback<TEvent>`

  The function to be called on event.

* `options?: GetCallbackOptions<TEvent>`

  Additional options.

#### Returns

* `void`

<a id="function-render">

### `render() → HTMLElement | Text`

Renders a DOM Node (an HTML element or text) out of the template.

```typescript
const domNode = new Template( { ... } ).render();
```

See: [`apply`](#function-apply).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L141)

#### Returns

* `HTMLElement | Text`

<a id="function-revert">

### `revert( node ) → void`

Reverts a template [applied](#function-apply) to a DOM node.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L211)

#### Parameters

* `node: HTMLElement | Text`

  The root node for the template to revert. In most of the cases, it is the same node used by [`apply`](#function-apply).

#### Returns

* `void`

<a id="function-stopDelegating">

### `stopDelegating( event?, emitter? ) → void` _(inherited)_

Stops delegating events. It can be used at different levels:

* To stop delegating all events.
* To stop delegating a specific event to all emitters.
* To stop delegating a specific event to a specific emitter.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L552)

#### Parameters

* `event?: string`

  The name of the event to stop delegating. If omitted, stops it all delegations.

* `emitter?: Emitter`

  (requires `event`) The object to stop delegating a particular event to. If omitted, stops delegation of `event` to all emitters.

#### Returns

* `void`

<a id="function-stopListening:BASE_STOP">

### `stopListening( emitter?, event?, callback? ) → void` _(inherited)_

Stops listening for events. It can be used at different levels:

* To stop listening to a specific callback.
* To stop listening to a specific event.
* To stop listening to all events fired by a specific object.
* To stop listening to all events fired by all objects.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L497)

#### Parameters

* `emitter?: Emitter`

  The object to stop listening to. If omitted, stops it for all objects.

* `event?: string`

  (Requires the `emitter`) The name of the event to stop listening to. If omitted, stops it for all events from `emitter`.

* `callback?: Function`

  (Requires the `event`) The function to be removed from the call list for the given `event`.

#### Returns

* `void`

<a id="function-_bindToObservable">

### `_bindToObservable( options = { options.data, options.schema, options.updater } ) → void` _(private)_

For a given [`TemplateValueSchema`](module_ui_template-TemplateValueSchema.md) containing [`TemplateBinding`](module_ui_template-TemplateBinding.md) activates the binding and sets its initial value.

Note: [`TemplateValueSchema`](module_ui_template-TemplateValueSchema.md) can be for HTML element attributes or text node `textContent`.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L800)

#### Parameters

* `options: object`

  Binding options.

  Properties

  * `options.data: RenderData`

    Rendering data.

  * `options.schema: Array<TemplateSimpleValue | TemplateBinding>`

  * `options.updater: Updater`

    A function which updates the DOM (like attribute or text).

#### Returns

* `void`

<a id="function-_renderAttributes">

### `_renderAttributes( data ) → void` _(private)_

Renders HTML element attributes out of [`attributes`](#member-attributes).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L515)

#### Parameters

* `data: RenderData`

  Rendering data.

#### Returns

* `void`

<a id="function-_renderElement">

### `_renderElement( data ) → HTMLElement | Text` _(private)_

Renders an HTML element out of the template.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L451)

#### Parameters

* `data: RenderData`

  Rendering data.

#### Returns

* `HTMLElement | Text`

<a id="function-_renderElementChildren">

### `_renderElementChildren( data ) → void` _(private)_

Recursively renders HTML element's children from [`children`](#member-children).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L715)

#### Parameters

* `data: RenderData`

  Rendering data.

#### Returns

* `void`

<a id="function-_renderNode">

### `_renderNode( data ) → HTMLElement | Text` _(private)_

Renders a DOM Node (either an HTML element or text) out of the template.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L415)

#### Parameters

* `data: RenderData`

  Rendering data.

#### Returns

* `HTMLElement | Text`

<a id="function-_renderStyleAttribute">

### `_renderStyleAttribute( styles, data ) → void` _(private)_

Renders the `style` attribute of an HTML element based on [`attributes`](#member-attributes).

A style attribute is an object with static values:

```typescript
attributes: {
	style: {
		color: 'red',
		'--color': 'red'
	}
}
```

or values bound to [`UIModel`](module_ui_model-UIModel.md) properties:

```typescript
attributes: {
	style: {
		color: bind.to( ... ),
		'--color': bind.to( ... )
	}
}
```

Note: The `style` attribute is rendered without setting the namespace. It does not seem to be needed.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L670)

#### Parameters

* `styles: Record<string, TemplateSimpleValue | TemplateBinding>`

  Styles located in `attributes.style` of [`TemplateDefinition`](module_ui_template-TemplateDefinition.md).

* `data: RenderData`

  Rendering data.

#### Returns

* `void`

<a id="function-_renderText">

### `_renderText( data ) → HTMLElement | Text` _(private)_

Renders a text node out of [`text`](#member-text).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L470)

#### Parameters

* `data: RenderData`

  Rendering data.

#### Returns

* `HTMLElement | Text`

<a id="function-_revertTemplateFromNode">

### `_revertTemplateFromNode( node, revertData ) → void` _(private)_

Reverts [template data](module_ui_template-RenderData.md#member-revertData) from a node to return it to the original state.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L833)

#### Parameters

* `node: HTMLElement | Text`

  A node to be reverted.

* `revertData: RevertData`

  An object that stores information about what changes have been made by [`apply`](#function-apply) to the node. See [`revertData`](module_ui_template-RenderData.md#member-revertData) for more information.

#### Returns

* `void`

<a id="function-_setUpListeners">

### `_setUpListeners( data ) → void` _(private)_

Activates `on` event listeners from the [`TemplateDefinition`](module_ui_template-TemplateDefinition.md) on an HTML element.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L771)

#### Parameters

* `data: RenderData`

  Rendering data.

#### Returns

* `void`

#### Static methods

<a id="static-function-bind">

### `bind( observable, emitter ) → BindChain<TObservable>` _(static)_

An entry point to the interface which binds DOM nodes to [observables](module_utils_observablemixin-Observable.md). There are two types of bindings:

* HTML element attributes or text `textContent` synchronized with attributes of an [`Observable`](module_utils_observablemixin-Observable.md). Learn more about [`to`](module_ui_template-BindChain.md#function-to:ATTRIBUTE) and [`if`](module_ui_template-BindChain.md#function-if).

```typescript
const bind = Template.bind( observable, emitter );

new Template( {
	attributes: {
		// Binds the element "class" attribute to observable#classAttribute.
		class: bind.to( 'classAttribute' )
	}
} ).render();
```

* DOM events fired on HTML element propagated through [`Observable`](module_utils_observablemixin-Observable.md). Learn more about [`to`](module_ui_template-BindChain.md#function-to:ATTRIBUTE).

```typescript
const bind = Template.bind( observable, emitter );

new Template( {
	on: {
		// Will be fired by the observable.
		click: bind( 'elementClicked' )
	}
} ).render();
```

Also see [`bindTemplate`](module_ui_view-View.md#member-bindTemplate).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L311)

#### Type parameters

* `TObservable: extends Observable`

#### Parameters

* `observable: TObservable`

  An observable which provides boundable attributes.

* `emitter: Emitter`

  An emitter that listens to observable attribute changes or DOM Events (depending on the kind of the binding). Usually, a [`View`](module_ui_view-View.md) instance.

#### Returns

* `BindChain<TObservable>`

<a id="static-function-extend">

### `extend( template, def ) → void` _(static)_

Extends an existing [`Template`](module_ui_template-Template.md) instance with some additional content from another [`TemplateDefinition`](module_ui_template-TemplateDefinition.md).

```typescript
const bind = Template.bind( observable, emitter );

const template = new Template( {
	tag: 'p',
	attributes: {
		class: 'a',
		data-x: bind.to( 'foo' )
	},
	children: [
		{
			tag: 'span',
			attributes: {
				class: 'b'
			},
			children: [
				'Span'
			]
		}
	]
 } );

// Instance-level extension.
Template.extend( template, {
	attributes: {
		class: 'b',
		data-x: bind.to( 'bar' )
	},
	children: [
		{
			attributes: {
				class: 'c'
			}
		}
	]
} );

// Child extension.
Template.extend( template.children[ 0 ], {
	attributes: {
		class: 'd'
	}
} );
```

the `outerHTML` of `template.render()` is:

```html
<p class="a b" data-x="{ observable.foo } { observable.bar }">
	<span class="b c d">Span</span>
</p>
```

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/template.ts#L392)

#### Parameters

* `template: Template`

  An existing template instance to be extended.

* `def: Partial<TemplateDefinition>`

  Additional definition to be applied to a template.

#### Returns

* `void`

---

Full index of the CKEditor 5 API reference: [llms.txt](llms.txt)
