HTML - Slot (Template Placeholder)

About

Slots allows to define placeholders in an HTML template

The technology Template, Shadow DOM and custom element are known under the term web components

Glossary

Status Description
Slotable The element that should be inserted in a slot
Sloted The element has been inserted in a slot

Properties

Name

Slots are identified by their name attribute

A named slot:

<slot name="attributes"><p>None</p></slot>

A step by step Example

Light DOM

The light DOM is a name that defined the HTML written in the page by the user.

Below this is the definition of our HTML page with a custom-element that we define programmatically later. This elements are called the light DOM.

We define the same custom element with two different content for demonstration purpose:

  • A custom element template based defined via javascript with a span slot elements that define the elements that will replaced in the slot placeholder of the template.
<custom-element>
  <span slot="slot-id">This text will replace the text in the template slot <mark>slot-id</mark></span>
</custom-element>
  • A second custom element that defines a ul slot elements that define the elements (ul,li) that will replace the slot placeholder of the template.
<custom-element>
    <ul slot="slot-id">
      <li>The replacement is done at element level</li>
      <li>Not on text level, you can then defined a list</li>
    </ul>
</custom-element>

Template

The template is an HTML elementthat defines the template with a slot. (This element is not rendered by any browser)

<template id="template-id">
    <style>
      p {
        color: white;
        background-color: #666;
        padding: 5px;
      }
    </style>
    <h2>Template with Slot</h2>
    <p><slot name="slot-id">The default text shown if the placeholder replacement is not done via javascript</slot></p>
</template>

Custom Element Definition

  • Javascript Custom Element Class definition that defines what to do when a custom-element is found in the HTML page.
customElements.define('custom-element',
  class extends HTMLElement {
    constructor() {
      super();

      const template = document.getElementById('template-id');
      const templateContent = template.content;

      this.attachShadow({mode: 'open'}).appendChild(
        templateContent.cloneNode(true)
      );
    }
  }
);

Observability

With Javascript, you can gain extra information on the template replacement with:

  • the slot
  • and assignedSlot attributes
const slottedSpan = document.querySelector('custom-element span');
console.log("Assigned/Replaced Slot Element: "+slottedSpan.assignedSlot.outerHTML);
console.log("Slot: "+slottedSpan.slot);

Result

Rendering

<slot>s do not move the user's light DOM (The HTML written by the user). When nodes are distributed into a <slot>, the <slot> renders their DOM but the nodes physically stay put.

Documentation / Reference


Powered by ComboStrap