Definition and Usage
The <template>
tag is used to define reusable pieces of HTML that can be cloned and inserted into the document later using JavaScript.
The content inside the <template>
tag is not rendered on the page but can be dynamically manipulated using JavaScript.
Basic Example
Let's explore a simple example.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The template Tag</title>
</head>
<body>
<h1>The template Tag</h1>
<p>
The content inside the template tag is not displayed during rendering
but can be dynamically manipulated using JavaScript.
</p>
<template id="list-item-template">
<li class="template-list-item"></li>
</template>
<ul id="template-item-list"></ul>
<button type="button" id="add-template-item-btn">Add Item</button>
<!-- JavaScript code is linked here -->
<script src="template.js"></script>
</body>
</html>
Explanation
- The visible content to users consists of the
<h1>
heading and the sentence: "The content inside the<template>
tag is not displayed during rendering but can be dynamically manipulated using JavaScript." - Below that, the
<template>
tag is defined. This tag serves as a template for list items to be used later. - There is an empty unordered list (
<ul>
) where items will be dynamically added. - Clicking the "Add Item" button triggers the JavaScript code.
JavaScript – template.js
const itemList = document.getElementById('template-list-item');
const listItemTemplate = document.getElementById('list-item-template');
const addItemBtn = document.getElementById('add-template-item-btn');
const predefinedItems = ['Apple', 'Banana', 'Orange', 'Grapes', 'Peach'];
addItemBtn.addEventListener('click', () => {
const randomIndex = Math.floor(Math.random() * predefinedItems.length);
const selectedText = predefinedItems[randomIndex];
const listItemClone = listItemTemplate.content.cloneNode(true);
const listItem = listItemClone.querySelector('.template-list-item');
listItem.textContent = selectedText;
itemList.appendChild(listItemClone);
});
Code Explanation
The textContent
property is used to get or set the text content of an HTML element.
Code Explanation
The appendChild()
method adds a node as the last child of a specified parent node.
How It Works
When the "Add Item" button is clicked, the JavaScript code runs. It randomly selects an item from the predefinedItems
array and dynamically adds the selected item to the list.
Live Demonstration
Try clicking the button! Each click randomly selects one of the following items: 'Apple', 'Banana', 'Orange', 'Grapes', or 'Peach', and dynamically adds it to the list.
The template Tag
The content inside the template tag is not displayed during rendering but can be dynamically manipulated using JavaScript.
This example demonstrates how to use the <template>
tag along with JavaScript to dynamically add list items to a web page.
Syntax
<template id="template-id">
<!-- Template content goes here -->
</template>
In this example:
- The
<template>
tag defines a reusable HTML template. - The optional
id
attribute assigns a unique identifier, which can be used to reference the tag in JavaScript. - The content placed inside the
<template>
tag is actual HTML markup. However, it is not rendered when the page loads. This content can be dynamically created or modified later using JavaScript.
Why Use the <template>
Tag?
Reusability and Maintainability
When the same layout or component needs to appear in multiple places, defining the structure in a template helps reduce code duplication and makes the project easier to maintain.
Handling Dynamic Data
Modern web applications often need to insert content based on user input or data fetched from a server. By combining the <template>
tag with JavaScript, you can efficiently manage data and generate content dynamically.
Improved Client-Side Rendering Performance
Instead of rendering all content on the server, you can shift part of the workload to the client. This approach can speed up the initial page load and improve overall user experience.
Managing Complex UI Interactions
When the user interface needs to update or change based on interactions, templates make it easier to control the UI with JavaScript. This approach simplifies dynamic UI updates.
Building Single Page Applications (SPAs)
Modern web apps often use a single-page architecture where page transitions don't involve full reloads. In these cases, templates help manage view updates and routing on the client side.
Using the <template>
tag together with JavaScript allows you to dynamically create and manage HTML content. This approach improves the performance, maintainability, and developer productivity of your web application.
Browser compatibility
Tag |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
---|---|---|---|---|
<template>
|
26 | 13 | 22 | 8 |
Specifications
Specification | |
---|---|
<template>
|
HTML Standard #the-template-element |