Intermediate LevelHTML & Semantic Web
How do <template> and <slot> elements enable Web Components encapsulation?
❓ Interview Prompt: Explain <template> un-rendered HTML fragments, Shadow DOM insertion, and <slot> content projection.
The '<template>' and '<slot>' elements provide the foundation for Web Components templating:
1. '<template>':
•
HTML markup enclosed in '<template>' is parsed by the browser but NOT rendered or executed until cloned via JavaScript ('document.importNode(template.content, true)').
2. '<slot>':
•
Acts as a placeholder inside a Web Component's Shadow DOM, allowing host light DOM markup to be projected into designated slot positions.
Code Implementation Example
html
<template id="user-card-template">
<style>
.card { padding: 1rem; border: 1px solid #ccc; }
</style>
<div class="card">
<h2><slot name="username">Default User</slot></h2>
</div>
</template>💡Web Component template definition with named slot projection.
🎯 Interview Key Takeaway
Use <template> to store un-rendered HTML markup fragments, and <slot> to project light DOM content into Shadow DOM trees.
#template#slot#Web Components#Intermediate
Back to all HTML & Semantic Web Questions→