HTML - HTML Template Element (<template>)
The <template> element in HTML is used to define reusable chunks of HTML code that are not immediately rendered when the page loads. It acts as a container for hidden HTML content that can later be activated and inserted into the document using JavaScript.
The content inside a <template> tag remains inactive until it is specifically requested. This makes it highly useful for dynamic web applications, reusable UI components, and modern frontend development.
Purpose of the <template> Element
The main purpose of the <template> element is to store HTML structures that can be reused multiple times without duplicating code in the document.
Before the introduction of <template>, developers often used hidden <div> elements or JavaScript strings to create reusable content. These approaches were harder to maintain and less efficient.
The <template> element solves these problems by providing:
-
Clean separation of reusable HTML
-
Improved performance
-
Easier DOM manipulation
-
Better maintainability
-
Support for dynamic UI generation
Basic Syntax
<template id="cardTemplate">
<div class="card">
<h2>Title</h2>
<p>Description goes here.</p>
</div>
</template>
The browser does not display this content automatically.
How the <template> Element Works
When the browser encounters a <template> element:
-
The content inside it is parsed by the browser.
-
The content is stored in memory.
-
The content is not rendered on the webpage.
-
JavaScript can later access and clone the content.
The template content is stored inside a special property called:
template.content
This property contains a DocumentFragment object.
Example of Using <template>
HTML
<template id="userTemplate">
<div class="user-card">
<h3 class="name"></h3>
<p class="email"></p>
</div>
</template>
<div id="container"></div>
JavaScript
const template = document.getElementById("userTemplate");
const clone = template.content.cloneNode(true);
clone.querySelector(".name").textContent = "John Doe";
clone.querySelector(".email").textContent = "[email protected]";
document.getElementById("container").appendChild(clone);
Output Explanation
Initially, the template content is hidden.
When JavaScript executes:
-
The template is selected.
-
Its content is cloned using
cloneNode(true). -
Data is inserted into the cloned elements.
-
The cloned content is appended to the webpage.
The final rendered output becomes:
<div class="user-card">
<h3>John Doe</h3>
<p>[email protected]</p>
</div>
Understanding cloneNode(true)
The cloneNode() method creates a duplicate of an element.
Syntax
cloneNode(deep)
Parameters
| Parameter | Meaning |
|---|---|
| true | Clones all child elements |
| false | Clones only the parent element |
Example:
const copy = template.content.cloneNode(true);
This creates a full copy of the template content.
What is DocumentFragment?
The content of a template is stored as a DocumentFragment.
A DocumentFragment is a lightweight container used to hold DOM nodes temporarily before inserting them into the actual document.
Benefits include:
-
Faster DOM updates
-
Reduced reflow and repaint operations
-
Improved performance
Advantages of Using <template>
1. Reusable HTML Structures
Templates allow developers to define a structure once and reuse it multiple times.
Example use cases:
-
Product cards
-
User profiles
-
Chat messages
-
Table rows
-
Notification boxes
2. Cleaner JavaScript
Without templates, developers often generate HTML using string concatenation.
Bad approach:
container.innerHTML += "<div>" + name + "</div>";
Using templates is cleaner and safer.
3. Better Performance
Since templates are not rendered immediately:
-
Browser rendering workload decreases
-
DOM updates become more efficient
4. Easier Maintenance
Updating one template automatically affects all future cloned instances.
5. Improved Code Organization
Templates separate UI structure from business logic.
Nested Templates
Templates can contain other templates.
Example:
<template id="outer">
<div>
<template id="inner">
<p>Nested Template</p>
</template>
</div>
</template>
Nested templates are useful in component-based applications.
Template with Loops
Templates are commonly used with arrays and loops.
Example:
<template id="productTemplate">
<div class="product">
<h2 class="title"></h2>
<p class="price"></p>
</div>
</template>
<div id="products"></div>
JavaScript
const products = [
{ title: "Laptop", price: "$900" },
{ title: "Phone", price: "$500" }
];
const template = document.getElementById("productTemplate");
const container = document.getElementById("products");
products.forEach(product => {
const clone = template.content.cloneNode(true);
clone.querySelector(".title").textContent = product.title;
clone.querySelector(".price").textContent = product.price;
container.appendChild(clone);
});
Output
<div class="product">
<h2>Laptop</h2>
<p>$900</p>
</div>
<div class="product">
<h2>Phone</h2>
<p>$500</p>
</div>
Template and Web Components
The <template> element is heavily used in Web Components.
It helps developers create custom reusable HTML elements.
Example:
<template id="myComponent">
<style>
p {
color: blue;
}
</style>
<p>Hello Component</p>
</template>
This template can later be attached to a Shadow DOM.
Combining <template> with Shadow DOM
Example:
class MyElement extends HTMLElement {
constructor() {
super();
const template = document.getElementById("myComponent");
const content = template.content.cloneNode(true);
const shadowRoot = this.attachShadow({ mode: "open" });
shadowRoot.appendChild(content);
}
}
customElements.define("my-element", MyElement);
Template vs Hidden Div
Before templates, developers used hidden divs:
<div id="template" style="display:none;">
<p>Hello</p>
</div>
Problems with this method:
-
Elements are still part of the active DOM
-
Slower rendering
-
Harder maintenance
-
Styling conflicts
The <template> element avoids these issues because its content remains inactive.
Browser Support
The <template> element is supported in all modern browsers:
-
Chrome
-
Firefox
-
Edge
-
Safari
-
Opera
Older browsers may require polyfills.
Common Use Cases
Dynamic UI Generation
Creating interface elements dynamically.
Single Page Applications
Frameworks like Angular, Vue, and Lit use template concepts extensively.
Data Rendering
Displaying API data in reusable layouts.
Component Libraries
Reusable design systems often rely on templates.
Repeated Structures
Useful for lists, cards, menus, and forms.
Limitations of <template>
1. Requires JavaScript
Template content does not appear without JavaScript interaction.
2. Initial Learning Curve
Developers unfamiliar with DOM manipulation may find it slightly advanced.
3. No Automatic Rendering
Unlike frameworks, HTML templates do not automatically bind data.
Best Practices
Use IDs for Template Selection
<template id="cardTemplate">
Keep Templates Modular
Create small reusable templates instead of very large ones.
Avoid Excessive Nesting
Too many nested templates can make code harder to read.
Use cloneNode(true)
This ensures all child elements are copied correctly.
Combine with Modern JavaScript
Templates work well with:
-
ES6 modules
-
Fetch API
-
Web Components
-
Shadow DOM
Real-World Example
A social media application may use templates for:
-
Posts
-
Comments
-
Notifications
-
Friend suggestions
Instead of writing repetitive HTML manually, one template can generate thousands of dynamic elements efficiently.
Conclusion
The <template> element is a powerful HTML feature used for storing reusable, inactive HTML structures. It improves performance, organization, maintainability, and dynamic rendering in modern web applications.
By combining <template> with JavaScript, developers can build efficient and scalable user interfaces without duplicating HTML code. It is especially important in modern frontend development, component-based design, and Web Component architecture.