Lesson 5 of 9
HTML Templates & Slots
The <template> element holds HTML that isn't rendered until you clone and insert it with JavaScript. Combined with <slot> for content projection, templates provide a declarative way to create reusable UI patterns without the overhead of a framework.
Template & Slot Usage
- <template> content is parsed but NOT rendered - invisible until cloned with JavaScript.
- Clone templates: template.content.cloneNode(true) creates a deep copy ready to insert into DOM.
- Templates avoid innerHTML security risks - pre-parsed by browser, not subject to XSS injection.
- <slot> elements in Shadow DOM let users inject custom content into component placeholders.
- Named slots: <slot name='header'> - Users inject with <div slot='header'>Content</div>.
- Default slot: <slot></slot> - Captures all content not assigned to a named slot.
- Fallback content: <slot>Default text</slot> - Shows 'Default text' if no content is slotted.
Diagram
Loading diagram…
template elements hold inert HTML markup until cloned and instantiated by JavaScript
Key Takeaways
- The <template> element holds HTML that isn't rendered until you clone and insert it with JavaScript.
- <template> content is parsed but NOT rendered - invisible until cloned with JavaScript.
- Clone templates: template.content.cloneNode(true) creates a deep copy ready to insert into DOM.
- Templates avoid innerHTML security risks - pre-parsed by browser, not subject to XSS injection.
Finished this lesson?
0 of 9 in Module 11