Template Tag; Dynamic Template Loading
Template Tag
The <template>
element in HTML is a powerful tool for defining reusable markup templates within Web Components. These templates are not rendered on the page but can be used to define the structure of your custom elements.
Example of using the <template>
element:
<template id="my-element-template">
<style>
:host { display: block; }
h1 { color: var(--heading-color, black); }
</style>
<h1><slot name="title">Default Title</slot></h1>
<p><slot>Default content</slot></p>
</template>
<script>
class MyElement extends HTMLElement {
constructor() {
super();
const template = document.getElementById('my-element-template');
const templateContent = template.content.cloneNode(true);
this.attachShadow({ mode: 'open' }).appendChild(templateContent);
}
}
customElements.define('my-element', MyElement);
</script>
In this example, the <template>
element is used to define the structure and styling of the <my-element>
custom element. The content of the template is then cloned and attached to the component's shadow root.
Dynamic Template Loading
You can also load templates dynamically, for example, from a separate HTML file. This allows you to keep your component's markup separate from the JavaScript code, promoting better modularity and maintainability.
class DynamicElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
connectedCallback() {
this.loadTemplate('dynamic-element-template.html')
.then(templateContent => {
this.shadowRoot.appendChild(templateContent.cloneNode(true));
});
}
async loadTemplate(url) {
const response = await fetch(url);
const html = await response.text();
const template = document.createElement('template');
template.innerHTML = html;
return template.content;
}
}
customElements.define('dynamic-element', DynamicElement);
In this example, the DynamicElement
class loads its template from a separate file, dynamic-element-template.html
, using the loadTemplate()
method. This method fetches the HTML content, creates a <template>
element, and returns the template's content.
By separating the template from the component's JavaScript, you can make your code more modular and easier to maintain.