Implementation of HTML Templates and Slots for Web Components
<template> and <slot> are two HTML elements that complement Custom Elements and Shadow DOM. Templates allow describing component structure directly in HTML without execution. Slots enable inserting external content inside Shadow DOM.
HTML Template
Contents of <template> are parsed by browser but not rendered or executed. Images are not loaded, scripts not executed, styles not applied — until cloning.
<!-- In HTML document or component file -->
<template id="card-template">
<style>
.card {
padding: 24px;
border-radius: 12px;
background: var(--card-bg, #fff);
box-shadow: 0 2px 16px rgba(0,0,0,0.08);
}
.card__header {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 16px;
}
.card__avatar {
width: 48px;
height: 48px;
border-radius: 50%;
object-fit: cover;
}
.card__body {
line-height: 1.6;
}
</style>
<div class="card">
<div class="card__header">
<img class="card__avatar" src="" alt="">
<div class="card__meta">
<slot name="name"><strong>Name not specified</strong></slot>
<slot name="role"><em>Role not specified</em></slot>
</div>
</div>
<div class="card__body">
<slot>Description not specified</slot>
</div>
</div>
</template>
class TeamCard extends HTMLElement {
private shadow: ShadowRoot
constructor() {
super()
this.shadow = this.attachShadow({ mode: 'open' })
}
connectedCallback() {
// Get template and clone
const template = document.getElementById('card-template') as HTMLTemplateElement
const clone = template.content.cloneNode(true) as DocumentFragment
// Set data from attributes
const avatar = clone.querySelector('.card__avatar') as HTMLImageElement
avatar.src = this.getAttribute('avatar') || '/placeholder.png'
avatar.alt = this.getAttribute('name') || 'Photo'
this.shadow.appendChild(clone)
}
}
customElements.define('team-card', TeamCard)
Usage:
<team-card avatar="/team/anna.jpg">
<strong slot="name">Anna Kovaleva</strong>
<span slot="role">Lead Frontend Engineer</span>
Specializes in React architecture and WebGL visualizations.
</team-card>
Template Inside Component (String Approach)
If template is not needed in HTML — use programmatic creation:
// Create template once on class definition (not in constructor)
const template = document.createElement('template')
template.innerHTML = `
<style>
:host {
display: inline-flex;
align-items: center;
gap: 8px;
}
.badge {
padding: 4px 10px;
border-radius: 100px;
font-size: 12px;
font-weight: 600;
letter-spacing: 0.03em;
}
:host([color="green"]) .badge { background: #d4edda; color: #155724; }
:host([color="red"]) .badge { background: #f8d7da; color: #721c24; }
:host([color="blue"]) .badge { background: #d1ecf1; color: #0c5460; }
:host([color="yellow"]) .badge { background: #fff3cd; color: #856404; }
</style>
<span class="badge">
<slot></slot>
</span>
`
class StatusBadge extends HTMLElement {
constructor() {
super()
const shadow = this.attachShadow({ mode: 'open' })
// Clone template — don't recreate DOM each time
shadow.appendChild(template.content.cloneNode(true))
}
}
customElements.define('status-badge', StatusBadge)
Advantage: template created once, cloning faster than repeated innerHTML.
Slots: Named and Default
<template id="dialog-template">
<style>
.dialog-backdrop {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.dialog {
background: #fff;
border-radius: 16px;
padding: 0;
max-width: 480px;
width: 90%;
overflow: hidden;
}
.dialog__header {
padding: 20px 24px;
border-bottom: 1px solid #eee;
font-weight: 700;
font-size: 18px;
}
.dialog__body {
padding: 24px;
}
.dialog__footer {
padding: 16px 24px;
border-top: 1px solid #eee;
display: flex;
justify-content: flex-end;
gap: 12px;
}
/* If footer slot is empty — hide */
.dialog__footer:not(:has(slot[name="footer"] ~ *)):empty {
display: none;
}
</style>
<div class="dialog-backdrop">
<div class="dialog" role="dialog" aria-modal="true">
<div class="dialog__header">
<!-- Named slot with fallback content -->
<slot name="title">Dialog</slot>
</div>
<div class="dialog__body">
<!-- Default slot — all content without slot attribute -->
<slot></slot>
</div>
<div class="dialog__footer">
<!-- Optional footer slot -->
<slot name="footer"></slot>
</div>
</div>
</div>
</template>
<modal-dialog id="confirm-modal">
<span slot="title">Confirm deletion</span>
<p>This action cannot be undone. Are you sure?</p>
<div slot="footer">
<button onclick="document.getElementById('confirm-modal').close()">
Cancel
</button>
<button onclick="handleDelete()">Delete</button>
</div>
</modal-dialog>
Slotchange — Reaction to Slot Changes
class DynamicList extends HTMLElement {
private shadow: ShadowRoot
private countEl!: HTMLElement
constructor() {
super()
this.shadow = this.attachShadow({ mode: 'open' })
this.shadow.innerHTML = `
<style>
.list-header { display: flex; justify-content: space-between; }
.count { opacity: 0.5; font-size: 14px; }
</style>
<div class="list-header">
<slot name="heading"></slot>
<span class="count"></span>
</div>
<slot></slot>
`
this.countEl = this.shadow.querySelector('.count')!
}
connectedCallback() {
const defaultSlot = this.shadow.querySelector('slot:not([name])')!
// Listen to content change in default slot
defaultSlot.addEventListener('slotchange', () => {
const items = (defaultSlot as HTMLSlotElement).assignedElements()
this.countEl.textContent = `${items.length} items`
})
}
}
Programmatic Access to Slots
// Get all elements in slot
const slot = this.shadow.querySelector('slot[name="items"]') as HTMLSlotElement
const assigned = slot.assignedElements()
// or including text nodes:
const nodes = slot.assignedNodes({ flatten: true })
// Check if slot has content
const hasContent = slot.assignedElements().length > 0
this.shadow.querySelector('.footer')?.toggleAttribute('hidden', !hasContent)
Template with id and data Attributes
Templates for lists, where each element clones with data:
// Render list via template
function renderProductList(products: Product[], container: HTMLElement) {
const template = document.getElementById('product-item-tpl') as HTMLTemplateElement
// DocumentFragment for batch insert
const fragment = document.createDocumentFragment()
products.forEach((product) => {
const clone = template.content.cloneNode(true) as DocumentFragment
;(clone.querySelector('.product-name') as HTMLElement).textContent = product.name
;(clone.querySelector('.product-price') as HTMLElement).textContent =
new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' })
.format(product.price)
;(clone.querySelector('.product-img') as HTMLImageElement).src = product.image
const addBtn = clone.querySelector('.add-to-cart') as HTMLButtonElement
addBtn.dataset.id = String(product.id)
fragment.appendChild(clone)
})
container.innerHTML = ''
container.appendChild(fragment) // Single DOM insert
}
Timeframes
Couple of components with templates and slots — 1 day. Full component system (5–8 components) with programmatic slot access, slotchange handlers and documentation — 1 week.







