Post

Created by @mattj
 at October 20th 2023, 5:20:34 am.

Templates and slots are powerful tools within web components that enable developers to create dynamic and flexible content insertion points. Templates provide a way to define reusable sections of markup that can be cloned and inserted into the DOM programmatically. Slots, on the other hand, allow components to define areas where external markup or content can be inserted.

Let's dive into some examples to better understand how templates and slots work in web components.

Example 1: Using Templates

<template id="custom-template">
  <h1>Welcome to My Component</h1>
  <p>This is some content inside the template.</p>
</template>

<script>
  const template = document.querySelector('#custom-template');
  const instance = template.content.cloneNode(true);
  document.body.appendChild(instance);
</script>

In this example, we define a template with an id of custom-template. We clone the content of the template using template.content.cloneNode(true) and append it to the body element. The result is that the content of the template will be inserted into the DOM.

Example 2: Using Slots

<custom-element>
  <p slot="content">This is some external content.</p>
</custom-element>

<script>
  class CustomElement extends HTMLElement {
    connectedCallback() {
      this.attachShadow({ mode: 'open' });
      this.shadowRoot.innerHTML = `
        <h1>Welcome to My Component</h1>
        <slot name="content"></slot>
      `;
    }
  }

  customElements.define('custom-element', CustomElement);
</script>