静的サイトジェネレータやアプリケーションフレームワークでは、webページを作成する際にテンプレートと内容を分けることができることがほとんどです。Web Componentsという技術を使うことで、アプリケーションフレームワークなどを使用せずに、同様のことが可能です。
<template>
を使用してカスタム要素の内容を定義します。これを行うことで要素の再利用が可能になります。
<slot>
を使用して外部から値を与えることもできます。
<template id="custom-element-template">
<p><slot name="custom-element-text">default text</slot></p>
<button>this is button</button>
</template>
WebAPIを使用してカスタム要素を登録します。
customElements.define('custom-element', class extends HTMLElement {
constructor() {
super();
const customElement = document.querySelector('#custom-element-template').content;
if (this.hasAttribute('text')) {
customElement.textContent = this.getAttribute('text');
}
const shadowRoot = this.attachShadow({mode: 'open'}).appendChild(customElement.cloneNode(true));
};
});
カスタム要素を表示します。入れ子にする場合、 <slot>
を使用しない要素は表示されません。
<custom-element>
<span slot="custom-element-text">this is custom element</span>
<span>this is not display</span>
</custom-element>