Chapter 8: Working with templates and slots
The introduction explains why inline web-component markup may become less suitable as components and applications grow, then previews the chapter’s alternatives.
After this chapter you will be able to
- Limits of inline component markup. Explain why loading HTML inline in a web component’s JavaScript may become less suitable as an application and its components grow more complex.
- Inert template content. Explain what happens to markup inside a <template> before it is used: the browser parses it, but does not render or execute it during initial page loading.
- Reusable markup blueprints. Describe why a <template> is useful for repeated HTML and how that markup becomes part of the page.
- Template lookup and insertion. Trace how a declared <template> becomes visible: locate it by ID, access its content DocumentFragment, then clone and insert the clone rather than the original content.
- Fragment consumption and reuse. Explain why inserting the same template content twice does not produce two copies and why cloning is needed for reuse.
- Two template cloning methods. Distinguish template.content.cloneNode(true) from document.importNode(template.content, true), including when the copied nodes become owned by the destination document.
- Reusable markup and separation. Explain how keeping markup in HTML templates separates it from JavaScript and lets one template be cloned repeatedly instead of rebuilding the DOM each time.
- Parsed but inert content. Explain the safety and performance benefits described for template content: the browser parses it, but its contents do not fetch resources or run scripts until used.
- Web component markup options. Describe why a web component may need static markup and encapsulated styles, and name the three setup patterns presented: programmatic DOM creation, cloning an HTML-document template, or loading an external HTML file with JavaScript.
- Document template for component content. Describe how the product-card example places its markup and styles in a <template> in the main HTML document, and why this approach suits server-rendered apps.
- External template loading and reuse. Explain how a web component can fetch a template from an external HTML file and reuse a cached, parsed template across instances instead of fetching it for each one.
- Loading and error placeholders. Explain why an externally fetched template may initially leave a component empty, and describe how alternative content can cover loading or download errors.
- Template stylesheet loading delay. Explain why a template that uses an external stylesheet can briefly render without its styles.
- FOUC reduction strategies. Describe ways to reduce FOUC when using templates with external stylesheets, including what must happen if a component stays in a loading state.
- Dynamic data in parsed templates. Explain why variable replacement in a JavaScript template string does not directly work for content already parsed in a <template>, and describe filling that content through DOM placeholders instead.
- Cloning templates for collections. Describe how to render repeated items by cloning an HTML template for each entry in a data array and updating the clone’s text nodes.
- Template engine rendering pattern. Explain how a template engine takes a template and data object, replaces placeholders, handles template logic, and produces markup for a component’s shadow DOM.
- Reusable placeholder interpolation. Describe the section’s simple custom interpolation approach: find double-curly-brace placeholders with a regular expression, match a placeholder such as {{ name }} to data, and use a shareable interpolate helper with TreeWalker to traverse nodes.
- Community Engine Adoption Tradeoffs. Justify when a community template engine is worth adding instead of using the simple interpolate function.
- Template Rendering Approach Differences. Distinguish string-based engines from tagged-template-literal libraries by how they render updates, and describe what precompilation changes for string-based engines.
- Rendered Markup Placement. Describe how rendered output reaches a web component’s shadow root for string-based engines versus tagged-template-literal libraries.
- Slot content projection. Explain how a <slot> marks a place in shadow DOM for content supplied as children of a custom element. Describe how different instances can supply different content while sharing the component’s surrounding markup.
- Default and named slot assignment. Distinguish how children are assigned to an unnamed default slot versus a named slot, including how the slot and child attributes match.
- Slot fallback visibility. Explain where fallback content is placed and when it appears or disappears as a consumer supplies matching content.
- Named slot content placement. Explain how the product-details component displays consumer-provided title, description, and action content, including what happens when the action button is omitted.
- Flattened tree and DOM location. Explain how the flattened tree combines shadow DOM with projected light DOM for rendering while the page DOM children remain in their original location.
- Multiple children in one slot. Explain that a slot can receive multiple children and renders them in order when they have a matching slot attribute, or no slot attribute for the default slot.
- Styling origin of slotted content. Explain that slotted content is styled by the document where it is defined, not by the shadow DOM where it is projected. Describe how a class from the main document can still style a slotted element.
- Direct-child styling boundary. Explain that ::slotted() lets shadow DOM style slotted content but selects only direct children, not their descendants, to preserve encapsulation.
- Slotted content styling strategies. Describe the three approaches named for styling when ::slotted() is limited: style the slot’s container, use CSS custom properties as a styling bridge, or tell consumers which classes or styles to apply to their slotted content.
- Slotchange event triggers. Explain that slotchange fires on a <slot> when its directly assigned nodes change, including additions, removals, or changes to a node’s slot attribute, but not when children of those nodes change.
- Assigned node and element methods. Distinguish what assignedNodes(options) and assignedElements(options) return for a <slot>.
- Flattening nested slot content. Explain what the flatten: true option changes when retrieving content from nested slots.
- Dynamic tabs from slotted panels. Explain how the tab container uses its slotted panels to create tab buttons and keep them up to date.
- Finding an element’s assigned slot. Explain that an element from the main document exposes an assignedSlot property that returns the slot it is projected into, allowing traversal from light DOM content back to its projection point.
- Nested slot content flow. Trace how content assigned to an outer component’s slot can be passed into an inner component’s slot.
- Clear slot interface. Explain why slots should have descriptive names and why available slots and their expected content should be documented.
- Optional customization boundaries. Distinguish optional content suited to slots from content required for a component to function.
What it builds on
- Rendering content (chapter 7) · Assumes the earlier approach of rendering content in web components.
- The DOM tree (chapter 6) · Assumes the distinction between DOM nodes and the page’s live DOM.
- Creating elements (chapter 6) · Assumes that JavaScript can add nodes to the DOM.
- Shadow DOM (chapter 7) · Assumes familiarity with shadow DOM as part of web component development.
- Registration (chapter 7) · Registration of custom elements.
- Custom Elements API (chapter 7) · Creating web components with the Custom Elements API.
- Styles with Shadow DOM (chapter 7) · Assumes prior discussion of styles with Shadow DOM.
- Browsing the tree (chapter 6) · Assumes familiarity with traversing the DOM tree.
Section by section
Introduction
The introduction explains why inline web-component markup may become less suitable as components and applications grow, then previews the chapter’s alternatives.
- Limits of inline component markup: Explain why loading HTML inline in a web component’s JavaScript may become less suitable as an application and its components grow more complex.
Why it matters: This is the reason the chapter looks beyond inline component markup.
Key terms: web components, innerHTML, DOM APIs
8.1 The Template Content HTML Element
This section introduces <template> as an inert, reusable HTML blueprint and explains how it relates to web components.
- Inert template content: Explain what happens to markup inside a <template> before it is used: the browser parses it, but does not render or execute it during initial page loading.
Why it matters: It explains why you can keep markup in a page without displaying or activating it immediately. - Reusable markup blueprints: Describe why a <template> is useful for repeated HTML and how that markup becomes part of the page.
Why it matters: It gives you a way to reuse HTML without constructing each copy as a string or keeping a hidden rendered example. - Web component relationship: Distinguish templates from required web component features while describing their common use together.
Why it matters: It prevents you from treating templates as mandatory whenever you build a web component.
Key terms: <template>, DocumentFragment, live DOM, clone, structure, logic, Template Content elements, Custom Elements, shadow DOM
8.1.1 Usage
This section shows how to find a <template>, clone its content, and insert visible, independently modifiable instances into the DOM.
- Template lookup and insertion: Trace how a declared <template> becomes visible: locate it by ID, access its content DocumentFragment, then clone and insert the clone rather than the original content.
Why it matters: This is the basic sequence for turning reusable template markup into visible page content. - Independent cloned instances: Explain why cloned template nodes can be modified without changing other instances made from the same template.
Why it matters: One template can supply multiple rows whose contents can differ.
Key terms: <template>, id, content property, DocumentFragment, clone, template, cloned nodes, instances
8.1.2 The Need for Cloning Templates
This section explains why reusable template content must be cloned, how the two cloning methods differ, and what cloning means for inert content, custom elements, and event listeners.
- Fragment consumption and reuse: Explain why inserting the same template content twice does not produce two copies and why cloning is needed for reuse.
Why it matters: It explains why a template can appear to work once and then produce nothing on later insertions. - Two template cloning methods: Distinguish template.content.cloneNode(true) from document.importNode(template.content, true), including when the copied nodes become owned by the destination document.
Why it matters: Either method supplies a fresh set of nodes without consuming the template’s content. - Inert content and upgrades: Explain why template content does not render or run while held in the template, and what triggers a copied custom element to upgrade.
Why it matters: It separates making a copy from connecting that copy and activating a registered custom element. - Listeners on cloned nodes: Explain why data or event listeners should not be attached to template.content and where listeners should be attached instead.
Why it matters: It prevents listeners from being placed on an emptied fragment or assumed to transfer to new nodes.
Key terms: template.content, DocumentFragment, clone, cloneNode(true), document.importNode, deep copy, adopted, inert document, contents owner document, custom element
8.1.3 Advantages
This section explains why templates are useful for reusable markup, how their inert content behaves, and why they should not be used merely to hide content.
- Reusable markup and separation: Explain how keeping markup in HTML templates separates it from JavaScript and lets one template be cloned repeatedly instead of rebuilding the DOM each time.
Why it matters: You can reuse UI markup without mixing it into JavaScript strings or repeatedly constructing the same DOM. - Parsed but inert content: Explain the safety and performance benefits described for template content: the browser parses it, but its contents do not fetch resources or run scripts until used.
Why it matters: A template can hold parsed markup without immediately loading its resources or running its scripts. - Limits of hiding with templates: Explain why a template should not be used solely to hide content, and name the alternatives given.
Why it matters: Not appearing on screen does not make template content an appropriate way to hide content.
Key terms: separation of concerns, reduced duplication, template, cloned, parsed, inert, network requests, assistive technologies, search engines, hidden
8.2 Using Templates in Web Components
Introduces why web components need reusable markup and styles and identifies three ways to provide their markup.
- Web component markup options: Describe why a web component may need static markup and encapsulated styles, and name the three setup patterns presented: programmatic DOM creation, cloning an HTML-document template, or loading an external HTML file with JavaScript.
Why it matters: These options frame the different ways to supply reusable component markup.
Key terms: Web Components, encapsulated styles, DOM API, <template>, custom element
8.2.1 Defining a Template in the HTML document
Shows how a web component can use a template declared in the main HTML document and notes a limit of changing that template after cloning.
- Document template for component content: Describe how the product-card example places its markup and styles in a <template> in the main HTML document, and why this approach suits server-rendered apps.
Why it matters: It gives you a way to keep component content in the HTML delivered with the page. - Cloned template update behavior: Explain what happens to clones already in the DOM if the original <template> element’s contents are changed.
Why it matters: It prevents the mistaken expectation that editing the source template will refresh existing component content.
Key terms: <template> element, main HTML document, web components, server-rendered apps, clones, DOM
8.2.2 Using external HTML files
This section explains how web components can load templates from external HTML files, reuse the loaded template, and handle loading and error states.
- External template loading and reuse: Explain how a web component can fetch a template from an external HTML file and reuse a cached, parsed template across instances instead of fetching it for each one.
Why it matters: Reusing one loaded template is especially helpful when an application has many instances of a component. - Loading and error placeholders: Explain why an externally fetched template may initially leave a component empty, and describe how alternative content can cover loading or download errors.
Why it matters: A placeholder avoids leaving users with an empty component while its template loads or fails. - Shared template loading base class: Describe how a base class can centralize external-template loading for multiple components, and state what a subclass must do if it overrides connectedCallback.
Why it matters: A shared base class keeps the loading behavior consistent without repeating it in every component. - Other template delivery options: Distinguish fetching an external template from the other delivery options noted here, including build-time bundler imports and Declarative Shadow DOM.
Why it matters: These distinctions help you recognize when fetching a template is not the only available choice.
Key terms: external HTML files, Fetch API, parsed template, static variable, connectedCallback, loading message, error, alternative content, base class, ExternalTemplateElement
8.2.3 Loading external CSS stylesheets
This section explains why external stylesheets in templates can cause a flash of unstyled content and outlines ways to reduce it.
- Template stylesheet loading delay: Explain why a template that uses an external stylesheet can briefly render without its styles.
Why it matters: It explains why a component may appear unstyled even though its template includes a stylesheet. - FOUC reduction strategies: Describe ways to reduce FOUC when using templates with external stylesheets, including what must happen if a component stays in a loading state.
Why it matters: These choices help prevent users from seeing a component before its intended styling is ready.
Key terms: <template>, FOUC, Flash of Unstyled Content, external stylesheets, CSSStyleSheet, adopted stylesheets, <style>, preload, loading state
8.3 Rendering Dynamic Data in Templates
Explains how to put dynamic data into pre-parsed HTML templates by filling DOM placeholders or cloning a template for each item in a collection.
- Dynamic data in parsed templates: Explain why variable replacement in a JavaScript template string does not directly work for content already parsed in a <template>, and describe filling that content through DOM placeholders instead.
Why it matters: This lets a component vary its content while working with the template’s parsed DOM. - Cloning templates for collections: Describe how to render repeated items by cloning an HTML template for each entry in a data array and updating the clone’s text nodes.
Why it matters: It provides a way to render lists, such as shopping-cart items, from one reusable template.
Key terms: <template>, DOM API, textContent, data-fill, innerHTML, clone, fragment, text nodes, <cart-summary>
8.3.1 Creating a Custom Template Engine
This section explains the template-engine rendering pattern and sketches a reusable interpolation helper for web components.
- Template engine rendering pattern: Explain how a template engine takes a template and data object, replaces placeholders, handles template logic, and produces markup for a component’s shadow DOM.
Why it matters: This pattern separates a component’s markup from the data used to fill it. - Reusable placeholder interpolation: Describe the section’s simple custom interpolation approach: find double-curly-brace placeholders with a regular expression, match a placeholder such as {{ name }} to data, and use a shareable interpolate helper with TreeWalker to traverse nodes.
Why it matters: A shared helper avoids writing the same property-by-property replacement code for each component.
Key terms: template engine, template, data object, rendering function, shadow DOM, interpolate, double curly braces, regular expression, TreeWalker
8.3.2 Using Community Template Engines
This section explains when a community template engine is worth using in a web component, how rendering approaches differ, and where JSX fits.
- Community Engine Adoption Tradeoffs: Justify when a community template engine is worth adding instead of using the simple interpolate function.
Why it matters: It helps you avoid adding a library when a small function already meets the component’s needs. - Template Rendering Approach Differences: Distinguish string-based engines from tagged-template-literal libraries by how they render updates, and describe what precompilation changes for string-based engines.
Why it matters: The rendering approach affects which engine suits a frequently updated component. - Rendered Markup Placement: Describe how rendered output reaches a web component’s shadow root for string-based engines versus tagged-template-literal libraries.
Why it matters: Generating markup is not the same as placing it in the component. - JSX Compilation Tradeoff: Explain how JSX can create DOM for vanilla web components and why it is not a browser-native, build-free option.
Why it matters: It clarifies that React is not required for JSX, but a compilation step is.
Key terms: interpolate function, community template engine, partials, string-based engines, tagged template literal libraries, precompilation, lit-html, Mustache, shadow root, light DOM
8.4 Using Slots
Introduces slots as customization points in a web component’s shadow DOM and explains how default and named slots receive content.
- Slot content projection: Explain how a <slot> marks a place in shadow DOM for content supplied as children of a custom element. Describe how different instances can supply different content while sharing the component’s surrounding markup.
Why it matters: Slots let a reusable component keep its structure while callers choose some of its content. - Default and named slot assignment: Distinguish how children are assigned to an unnamed default slot versus a named slot, including how the slot and child attributes match.
Why it matters: The assignment rules determine where a component user’s content appears.
Key terms: <slot>, shadow DOM, light DOM distribution, content projection, unnamed slot, default slot, named slot, name attribute, slot attribute
8.4.1 Fallback Content
This subsection explains when a slot displays its fallback content instead of content supplied by the page.
- Slot fallback visibility: Explain where fallback content is placed and when it appears or disappears as a consumer supplies matching content.
Why it matters: Fallback content lets a component show something by default without competing with content supplied by its consumer.
Key terms: slot, fallback content, page DOM, projected
8.4.2 Full example
A product-details example shows how named slots place consumer content, how fallback content appears, and how to inspect slot projection in developer tools.
- Named slot content placement: Explain how the product-details component displays consumer-provided title, description, and action content, including what happens when the action button is omitted.
Why it matters: This lets a component offer distinct places for supplied content while retaining a default action. - Slot projection inspection: Describe how browser developer tools can show the connection between projected markup and its slot in the rendered component.
Why it matters: These inspection cues help you see which supplied element is displayed through which slot.
Key terms: slots, product-details, fallback, slot projection, slot, reveal
8.4.3 The Flattened Tree
This subsection explains that slots affect a component’s rendered tree without moving page DOM children into the shadow DOM.
- Flattened tree and DOM location: Explain how the flattened tree combines shadow DOM with projected light DOM for rendering while the page DOM children remain in their original location.
Why it matters: It helps distinguish where slotted content appears from where its elements actually reside.
Key terms: flattened tree, shadow DOM, projected light DOM, page DOM children, slots
8.4.4 Multiple Elements in One Slot
This subsection explains that a slot can render multiple matching child elements in order.
- Multiple children in one slot: Explain that a slot can receive multiple children and renders them in order when they have a matching slot attribute, or no slot attribute for the default slot.
Why it matters: You can put several pieces of content into one slot without creating a separate slot for each piece.
Key terms: slot, slot attribute, default slot, projected
8.5 Styling Slotted Content
This section explains why slotted content keeps the styling of the document where it is defined, even when it appears inside a shadow DOM.
- Styling origin of slotted content: Explain that slotted content is styled by the document where it is defined, not by the shadow DOM where it is projected. Describe how a class from the main document can still style a slotted element.
Why it matters: It helps explain why a page’s styles can still affect content displayed through a component’s slot.
Key terms: slotted content, shadow DOM, projected
8.5.1 The ::slotted() pseudo-Element
Explains how ::slotted() styles slotted content and why its reach is limited.
- Direct-child styling boundary: Explain that ::slotted() lets shadow DOM style slotted content but selects only direct children, not their descendants, to preserve encapsulation.
Why it matters: This boundary helps you predict which parts of slotted content a component can style.
Key terms: shadow DOM, slotted content, ::slotted(), encapsulation
8.5.2 Styling Strategies
This subsection names practical ways to style slotted content when ::slotted() is limited.
- Slotted content styling strategies: Describe the three approaches named for styling when ::slotted() is limited: style the slot’s container, use CSS custom properties as a styling bridge, or tell consumers which classes or styles to apply to their slotted content.
Why it matters: These options give you ways to approach slotted-content styling without depending entirely on ::slotted().
Key terms: ::slotted(), slot’s container, CSS custom properties, slotted content
8.6 Slots API
8.6.1 The slotchange Event
This section explains when a slot’s slotchange event fires and which changes do not trigger it.
- Slotchange event triggers: Explain that slotchange fires on a <slot> when its directly assigned nodes change, including additions, removals, or changes to a node’s slot attribute, but not when children of those nodes change.
Why it matters: This distinction tells you which content changes a slotchange listener can detect.
Key terms: slotchange event, <slot>, direct nodes, slot attribute
8.6.2 assignedNodes and assignedElements
This subsection explains how to retrieve a slot’s projected content and how to get the content rendered through nested slots.
- Assigned node and element methods: Distinguish what assignedNodes(options) and assignedElements(options) return for a <slot>.
Why it matters: The distinction helps you choose whether to include text and comments when inspecting a slot’s content. - Flattening nested slot content: Explain what the flatten: true option changes when retrieving content from nested slots.
Why it matters: Flattening lets you inspect the content rendered through slots inside other slots.
Key terms: assignedNodes(options), assignedElements(options), projected content, flatten: true, nested <slot>, options object
8.6.3 Practical Example: Tab Component
This section illustrates how a tab component builds and updates its tab buttons from slotted panels.
- Dynamic tabs from slotted panels: Explain how the tab container uses its slotted panels to create tab buttons and keep them up to date.
Why it matters: It shows how a component can keep its controls in sync with the content placed in its slot.
Key terms: <tab-container>, Slots API, slotted panels, data-tab-title, slotchange
8.6.4 Finding a Slot’s Assigned Slot
This subsection shows how to find the slot into which a main-document element is projected.
- Finding an element’s assigned slot: Explain that an element from the main document exposes an assignedSlot property that returns the slot it is projected into, allowing traversal from light DOM content back to its projection point.
Why it matters: It lets you locate the slot associated with a piece of light DOM content.
Key terms: assignedSlot, light DOM, projection point
8.7 Nested Slots
This section explains how content passes through nested component slots and why deeply nested slot chains need care.
- Nested slot content flow: Trace how content assigned to an outer component’s slot can be passed into an inner component’s slot.
Why it matters: Following the content through both slots makes nested components easier to understand. - Nested slot hierarchy clarity: Explain why nested slot hierarchies should be documented and deep slot chains avoided when possible.
Why it matters: Clear slot hierarchies help others follow where content goes.
Key terms: nested slots, outer-component, inner-component, slot hierarchies, slot chains
8.8 Slot Best Practices
This section gives practical guidelines for designing slots that are clear, usable, and limited to appropriate customization points.
- Clear slot interface: Explain why slots should have descriptive names and why available slots and their expected content should be documented.
Why it matters: Clear names and documentation make a component’s customization points understandable to its consumers. - Usable fallback content: Explain why a slot should have meaningful fallback content when a consumer leaves it unfilled.
Why it matters: A component should remain useful when a consumer omits optional slotted content. - Shallow slot hierarchies: Explain why slot nesting should stay shallow and when to consider restructuring components.
Why it matters: Shallow slot structures are easier to understand and maintain. - Optional customization boundaries: Distinguish optional content suited to slots from content required for a component to function.
Why it matters: Choosing slots for optional content helps keep required component inputs explicit.
Key terms: slot name, public API, README, JSDoc, fallback content, slot hierarchies, nested slots, slots, attributes, properties
8.9 Summary
Where this is used later
- Lit for components (chapter 14) · Assumes familiarity with using templates in Web Components.
- Declarative Shadow DOM (chapter 9) · Develops the Declarative Shadow DOM option mentioned here.
- Binding with <template> (chapter 13) · Reuses the idea of binding data with <template>.
- Building a stateful component (chapter 9) · A slot can provide fallback content.
- Testing shadow DOM and slots (chapter 9) · The APIs for retrieving a slot’s assigned nodes and elements
Concepts explained in this chapter
- HTML template elementThe HTML <template> element holds inert markup that can later be cloned and inserted into a document or shadow DOM.
- slot elementThe HTML <slot> element defines an insertion point for content projected into a web component's shadow tree.
- named slotA named slot is a slot with a name attribute that receives only child nodes whose slot attribute has the matching value.
- DOM fragmentA lightweight DOM container that holds a subtree of nodes without being part of the document tree itself.
- fallbackAn alternative implementation or behavior used when a preferred feature or supplied content is unavailable.
- Document Object ModelThe browser programming interface for querying and manipulating a document's DOM representation.
- data attributeA custom HTML attribute whose name begins with data- and whose value stores application-specific information on an element.
- CSS variableA CSS custom property is an author-defined property whose value can be inherited and reused in CSS declarations through the var() function.
- light DOMThe DOM content supplied by a web component's host document rather than contained in the component's shadow tree.
- attributeA JavaScript property is a named value associated with an object.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
