HTML <template> Tag – Hidden Reusable Content
📌 Introduction
The <template> tag is used to define HTML content that is not displayed immediately when the page loads.
Instead, it is:
- Stored in the page
- Reused later with JavaScript
- Cloned and inserted dynamically
👉 Think of it as a “hidden blueprint” for HTML.
🧱 Syntax
<template>
<p>This is hidden content</p>
</template>
💡 Example (Basic)
<!DOCTYPE html>
<html>
<head>
<title>Template Example</title>
</head>
<body>
<h2>Users List</h2>
<template id="userTemplate">
<li>User Name</li>
</template>
<ul id="list"></ul>
<button onclick="addUser()">Add User</button>
<script>
function addUser() {
const template = document.getElementById("userTemplate");
const clone = template.content.cloneNode(true);
document.getElementById("list").appendChild(clone);
}
</script>
</body>
</html>
🖥️ Output Explanation
<template>content is NOT visible at first- JavaScript clones it
- Then it is inserted into the page
🎯 Why <template> is Important
1. 🧠 Reusable UI Blocks
You can create components like:
- Cards
- List items
- Rows
2. ⚡ No Page Rendering
Content stays hidden until needed.
3. 📦 Used in Modern Web Apps
Frameworks like React/Vue conceptually use similar ideas.
🧩 How It Works
template (hidden) → clone → insert into DOM
💡 Example (Card Template)
<template id="card">
<div class="item">
<h3>Title</h3>
<p>Description</p>
</div>
</template>
🎨 Styling Example
.item { border: 1px solid #ccc; padding: 10px; margin: 5px; }
⚖️ <template> vs <div>
| Feature | <template> |
<div> |
|---|---|---|
| Visible on load | ❌ No | ✔ Yes |
| Used for reuse | ✔ Yes | ❌ No |
| Requires JS | ✔ Usually | ❌ No |
🚫 Common Mistakes
- Expecting it to show on page load ❌
- Not using JavaScript to clone ❌
- Using it like a normal
<div>❌
🧪 Mini Exercise
Create a page with:
- A
<template>for a product card - A button to add cards
- Each click clones and adds a new card
- Style cards with borders and spacing