<template> Tag in HTML | Invisible Content for Reuse
The <template> tag in HTML is used to store HTML content that is not rendered on the page. Instead, this content is held in a reusable format, which can be accessed and dynamically inserted into the DOM using JavaScript. The template content remains hidden until explicitly referenced, making it useful for creating reusable UI components.
Key Points on <template> Tag:
- The <template> tag is a container for holding HTML code for future use.
- Content inside
<template>
is not displayed when the page loads. - Useful for dynamic content creation, allowing sections of HTML to be cloned and inserted multiple times in the DOM.
- Often used in conjunction with JavaScript to inject or clone template content into specific parts of the page.
Syntax of <template> Tag:
Syntax Example
<template>
<!-- Content to be reused -->
</template>
Example of <template> Tag in HTML:
This example demonstrates how to use the <template>
tag to create reusable content for a list of items.
Code Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Template Tag Example</title>
</head>
<body>
<h2>Product List</h2>
<ul id="productList"></ul>
<template id="productTemplate">
<li>Product Name</li>
</template>
<script>
const products = ["Product 1", "Product 2", "Product 3"];
const list = document.getElementById("productList");
const template = document.getElementById("productTemplate");
products.forEach((product) => {
const clone = template.content.cloneNode(true);
clone.querySelector("li").textContent = product;
list.appendChild(clone);
});
</script>
</body>
</html>
Output
Product List
- Product 1
- Product 2
- Product 3
Attributes of <template> Tag:
- id: Allows the template to be uniquely identified for easy access and cloning.
Advantages of Using <template> Tag:
- Reusability: Makes it easy to create reusable components that can be inserted multiple times.
- Improved Performance: Reduces HTML duplication, as templates are defined once and cloned as needed.
- Flexibility: Works well with JavaScript, allowing for dynamic content creation based on data.
- Separation of Concerns: Helps keep HTML structure separate from JavaScript logic and styling.
The <template>
tag is ideal for dynamically generating HTML content with JavaScript, offering a flexible and reusable approach to create consistent, data-driven elements in web applications.