Sub topic 4
Templates and slots in the platform
This chapter assumes you know basic HTML, JavaScript classes, and what a custom element with a shadow root is (from the previous chapters). It covers two built-in HTML elements, <template> and <slot>. Both exist in the browser without any framework. LWC uses both, so knowing the platform behavior explains what LWC does and what it only looks like it does.
The template element: inert markup
A <template> element holds markup that the browser parses but does not render. Its content differs from normal DOM content in these ways:
- Images in it do not load, scripts do not run, and styles do not apply.
- Its children are not in the page's DOM tree. They live in a
DocumentFragmenton the propertytemplate.content. - That fragment belongs to a separate, inert document, so
document.querySelectorcannot find anything inside it.
To use the markup, you clone the fragment and insert the copy. Each clone is a fresh, live set of nodes, so one template can produce many instances.
const tpl = document.createElement('template');
tpl.innerHTML = '<li class="row"></li>';
const list = document.createElement('ul');
for (const text of ['one', 'two', 'three']) {
const clone = tpl.content.cloneNode(true); // true = deep copy
clone.querySelector('.row').textContent = text;
list.appendChild(clone);
}
document.body.appendChild(list);Parse cost is paid once, and each copy is a cheap clone. This is why component libraries compile their markup into templates.
The slot element: a placeholder for outside content
A <slot> element only works inside a shadow tree. It marks a spot where the host element's children should appear. Those children are called light DOM children. They stay in the page's regular DOM and are owned by whoever wrote them. The browser displays them at the slot's position without moving them.
This is called slot assignment, and the result is the flattened tree. The flattened tree is what gets rendered, but it is never a real DOM structure you can query.
A complete example
This page defines a <user-card> element. The template supplies the shadow tree structure, and the page supplies the content through slots.
<!DOCTYPE html>
<html>
<body>
<template id="user-card-template">
<style>
.card { border: 1px solid #888; padding: 8px; width: 16rem; }
::slotted(h2) { margin: 0; color: darkblue; }
</style>
<div class="card">
<header><slot name="title">Untitled</slot></header>
<div><slot>No details provided.</slot></div>
</div>
</template>
<user-card>
<h2 slot="title">Ada Lovelace</h2>
<p>Mathematician</p>
</user-card>
<user-card></user-card>
<script>
class UserCard extends HTMLElement {
constructor() {
super();
const root = this.attachShadow({ mode: 'open' });
const tpl = document.getElementById('user-card-template');
root.appendChild(tpl.content.cloneNode(true));
}
}
customElements.define('user-card', UserCard);
</script>
</body>
</html>The first card shows both children in their slots. The second card has no children, so each slot shows its fallback content ("Untitled" and "No details provided.").
How assignment works
The rules below cover most surprises:
- Direct children only. Only direct children of the host are assigned. A
<span>inside the<p>is not slotted separately. It travels with its parent. - Default slot. Children with no
slotattribute go to the unnamed slot. This includes text nodes, so loose text inside the host appears there. - Named slots. A child with
slot="title"goes to the slot whosenameistitle. Several children with the same name are placed in document order. - Unmatched names. If no slot matches, the child is not rendered. It is still in the DOM, and you can still read it from script.
- Duplicate slot names. If two slots share a name, the first one in tree order receives the content.
- Fallback content. The children of a
<slot>show only when nothing is assigned to it. Whitespace-only text does not count as fallback-blocking in practice for named slots, but it does get assigned to the default slot. That can suppress the default slot's fallback, so trim whitespace if fallback matters. - No shadow root. A
<slot>outside a shadow tree does nothing.
Observing slots from script
Because slotted nodes stay in the light DOM, they are still reachable from the host. The slot also exposes what it received, and it fires slotchange when its assigned nodes change.
// Run after the page above has loaded.
const card = document.querySelector('user-card');
const slot = card.shadowRoot.querySelector('slot:not([name])');
slot.addEventListener('slotchange', () => {
const nodes = slot.assignedNodes({ flatten: true });
console.log('default slot now holds', nodes.length, 'node(s)');
});
const extra = document.createElement('p');
extra.textContent = 'Programmer';
card.appendChild(extra); // triggers slotchangeassignedNodes() returns text nodes too. assignedElements() returns only elements. With flatten: true, a slot nested inside another slot is replaced by its own assigned nodes, or by its fallback content if it has none. slotchange fires for assignment changes, not for changes deep inside a slotted node's own content.
Styling and events across the slot boundary
Slotted content belongs to the outer document, so the outer page's stylesheets style it. The shadow tree can reach it only through ::slotted(selector), which matches direct slotted elements and cannot select their descendants. Styles from the outside win over ::slotted rules when both set the same property.
Events from slotted content bubble through the slot, because the event path follows the flattened tree. A listener on an element in the shadow tree that wraps the slot will therefore see clicks on slotted children.
Where LWC fits
LWC uses these elements in two different ways.
| Element | Platform behavior | In LWC |
|---|---|---|
| `<template>` at the root of an `.html` file | Inert fragment you clone | A compile-time marker for the component's markup. The compiler turns it into JavaScript render code. It is not cloned from a native template element at runtime. |
| `<template>` with a directive such as `for:each` | Inert fragment | A wrapper that groups children without adding a DOM element. The directive decides how many times the children render. |
| `<slot>` | Placeholder in a shadow tree | Works the same way: named slots, default slot, fallback content, and `slotchange`. |
The next chapters cover the LWC syntax. For now, remember that the <template> tag in an LWC file looks like the platform element but is handled by the compiler. The <slot> tag is closer to the real thing, and the browser's assignment model is the one you reason about.
Common mistakes
- Querying
documentfor elements inside a template. They live intemplate.content, so usetpl.content.querySelector. - Appending
template.contentdirectly and expecting to reuse it. Appending moves the nodes out and leaves the fragment empty. Clone it first. - Putting a
slotattribute on a grandchild. It is ignored, because only direct children are assigned. - Expecting fallback content when the host contains whitespace or comments inside the default slot's range. Whitespace text nodes are assigned to the default slot.
- Styling slotted children with a shadow-tree selector such as
.card p. It does not match, because the<p>is not in the shadow tree. Use::slotted(p).
Exercise
In the user-card example, you add <p slot="subtitle">Pioneer</p> as a child of the first <user-card>, but the shadow template has no slot named subtitle. What does the user see, and can script still read that paragraph?
Show answer
The paragraph is not rendered, because no slot matches its name. It is still a child of the host in the light DOM, so card.querySelector('p[slot="subtitle"]') finds it. If you later add <slot name="subtitle"></slot> to the shadow tree, the paragraph is assigned to it and appears, and that slot fires slotchange.
Exercise
Why does tpl.content.cloneNode(true) have to be called each time you create a component instance, instead of appending tpl.content once and reusing it?
Show answer
Appending a DocumentFragment moves its children into the target and leaves the fragment empty. A second append would add nothing. Cloning gives each instance its own copy of the nodes, and the template stays intact for the next instance.