The <template>
tag in HTML is a powerful feature that allows you to create reusable HTML structures without immediately bloating the DOM. This makes it especially useful for dynamically generating repetitive content, such as a Facebook-style news feed or table rows.
π Do you like Techelopment? Check out the site for all the details!
What is the <template>
tag?
The <template>
tag defines a piece of HTML code that is not immediately rendered on the page. The content of the <template>
remains in the DOM but is not displayed until it is cloned and dynamically inserted into the page using JavaScript.
Advantages of using <template>
:
- Optimized performance: Elements defined in the template are not immediately loaded into the DOM, reducing the initial load of the page.
- Reusable code: Allows you to write HTML once and use it dynamically to generate new elements.
- Increased maintainability: By separating the structure from the insertion logic, the code becomes clearer and more modular.
Let's see some examples of use.
Dynamically Generating a News List
Let's imagine we want to create a news feed similar to a Facebook wall. Here's how <template>
can help us:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>News Feed with Template</title>
</head>
<body>
<h2>Latest News</h2>
<div id="news-container"></div>
<template id="news-template">
<div class="news-item">
<h3 class="title"></h3>
<p class="content"></p>
</div>
</template>
<script>
const newsData = [
{ title: "New feature released!", content: "Discover all the latest updates on our platform." },
{ title: "Special event tomorrow", content: "Don't miss the live-streamed event!" }
];
const template = document.getElementById('news-template');
const container = document.getElementById('news-container');
newsData.forEach(news => {
const clone = template.content.cloneNode(true);
clone.querySelector('.title').textContent = news.title;
clone.querySelector('.content').textContent = news.content;
container.appendChild(clone);
});
</script>
</body>
</html>
How it works:
- We define a
<template>
containing the markup for a single news item. - We create a
newsData
array with titles and contents. - We use JavaScript to clone the template and dynamically populate it with data.
- We append each element to the
#news-container
.
Here is the result:
Dynamic Table Row Generation
Another common scenario is dynamic table row generation, for example to display user data from a database.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table with Template</title>
</head>
<body>
<h2>User List</h2>
<table cellspacing="0">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody id="user-table">
</tbody>
</table>
<template id="row-template">
<tr>
<td class="name"></td>
<td class="age"></td>
</tr>
</template>
<script>
const users = [
{ name: "John Doe", age: 30 },
{ name: "Jane Smith", age: 25 }
];
const template = document.getElementById('row-template');
const tableBody = document.getElementById('user-table');
users.forEach(user => {
const clone = template.content.cloneNode(true);
clone.querySelector('.name').textContent = user.name;
clone.querySelector('.age').textContent = user.age;
tableBody.appendChild(clone);
});
</script>
</body>
</html>
How it works:
- We create an HTML table with an empty
<tbody>
. - We define a
<template>
for the rows of the table. - Using JavaScript, we clone and populate the template with user data, then add it to the table.
This is the result:
Note: Why use cloneNode(true)?
When we call cloneNode(true)
, the true
argument is essential because it ensures that the entire template subtree is cloned, including all child elements. If we were to use false, only the top-level template element would be copied, leaving its children empty. This is crucial when working with complex templates that contain nested elements.
Why use the <template>
tag
The <template>
tag in HTML is a powerful tool for dynamically creating content without immediately loading it into the DOM.
By using it, we can improve performance and keep the code clean and modular.
Whether it's graphical elements (like the news feed seen in the example) or data (like the users table we created), this technique optimizes rendering and efficiently handles dynamic elements.
Follow me #techelopment
Official site: www.techelopment.it
Medium: @techelopment
Dev.to: Techelopment
facebook: Techelopment
instagram: @techelopment
X: techelopment
Bluesky: @techelopment
telegram: @techelopment_channel
youtube: @techelopment
whatsapp: Techelopment
Top comments (10)
By using the <> enclosure in your title, the
< template >
part in the tile is not showing up in Google news feeds. Kind of how I had to add the space in the tag in this message so it wouldn't disappear in the HTML. Just thought I would let you know in case it was something you wanted to fix. I can send you the screenshot shot if you'd like. Nice article π
thank you, I would appreciate it so much π
It always amazes me what you can do with just raw HTML/JavaScript. It makes me often question the merits of frontend frameworks like React.
jsRender uses a similar arrangement, but allows simple merging of content, rather than having to iterate through every element in the cloned HTML.
wow, I'll try that!
I recently discovered the usefulness of HTML templates for a small status page I was creating. This is a great write-up and hopefully more people see that HTML, JS, & CSS can do a lot out of the box without frameworks.
While I wouldn't use as in the code examples, I would use it as progressive enhancement tool, html and javascript are great.
Thanks for the knowledge