
The <template> and <slot> elements are part of modern HTML (Web Components). They help developers create reusable, flexible UI components without immediately rendering content on the page. These elements are especially useful when building custom elements and design systems.
1. The <template> Element
The <template> tag is used to store HTML that is not displayed immediately when the page loads. The browser ignores its content until JavaScript explicitly activates it. Think of <template> as a blueprint for content.
Key points:
-
Content inside <template> is not visible
-
It does not affect page layout
-
Used mainly with JavaScript
-
Helps avoid repeated HTML
Example:
<template id="cardTemplate">
<div class="card">
<h2>Title</h2>
<p>Description text</p>
</div>
</template>
This content will not show on the page unless JavaScript clones and inserts it.
Why use <template>?
2. The <slot> Element
The <slot> tag is used inside custom components to define where external content should appear. It acts like a placeholder for user-provided content.
Key points:
Example (Custom Component):
<template id="boxTemplate">
<div class="box">
<slot></slot>
</div>
</template>
Using the component:
<my-box>
<p>This content goes into the slot</p>
</my-box>
The paragraph automatically appears where <slot> is placed.
3. Named Slots (Important)
Slots can be named to place content in specific locations.
Component template:
<slot name="title"></slot>
<slot name="content"></slot>
Usage:
<h2 slot="title">Card Title</h2>
<p slot="content">Card description</p>
This gives full layout control to the component.
4. Why <template> and <slot> Matter
Together, <template> and <slot> enable:
Simple takeaway:
They don’t replace normal HTML, but they power modern, component-based web development.