Course contentsShow
← Web Development
Lesson 2485 of 2,98244. Web ComponentsFree lesson

Templates and Slots Pattern: Reusable Component Markup

Combining <template> for structure and <slot> for customization to build flexible, declarative Web Components.

Templates and Slots Pattern: Reusable Component Markup

What you'll learn: How combining <template> and <slot> creates a powerful pattern for building flexible, declarative Web Components with pluggable content.

The Power of the Pattern

You've learned <template> provides inert, cloneable markup and <slot> enables content projection. Together, they form the Templates and Slots Pattern—the backbone of truly reusable Web Components.

Think of it like a sandwich maker: the <template> is your standardized bread and wrapper (the component's structure), while <slot> elements are cutouts where customers insert their choice of fillings. Every sandwich follows the same pattern, but each is customized.

How It Works

  1. Define structure once in a <template> with <slot> placeholders
  2. Clone the template in your component's constructor or connectedCallback
  3. Attach to shadow root for encapsulation
  4. Users provide content via Light DOM, which projects through slots
class CardComponent extends HTMLElement {
  connectedCallback() {
    const template = document.getElementById('card-template');
    const shadow = this.attachShadow({ mode: 'open' });
    shadow.appendChild(template.content.cloneNode(true));
  }
}

customElements.define('app-card', CardComponent);
<template id="card-template">
  <style>
    .card { border: 1px solid #ccc; padding: 1rem; }
  </style>
  <div class="card">
    <h2><slot name="title">Default Title</slot></h2>
    <slot>Default content</slot>
  </div>
</template>

<app-card>
  <span slot="title">Custom Title</span>
  <p>My custom content!</p>
</app-card>

The component defines its layout and styling once; users declare their content naturally in HTML without touching component internals.

Key Takeaway: The Templates and Slots Pattern combines <template> for repeatable structure with <slot> for content injection, enabling declarative, reusable Web Components where structure stays consistent while content remains flexible.