How to Use the HTML <template>
Tag
The <template>
tag in HTML is used to define a content template that can be used to render content on a webpage. The content inside a <template>
tag is not rendered when the page is loaded, but can be cloned and inserted into the document using JavaScript. This allows for a more efficient way to manage and render content on a webpage.
Example of Using the <template>
Tag:
<template id="userTemplate">
<div>
<h2>{{name}}</h2>
<p>{{email}}</p>
</div>
</template>
<script>
// Get the template element
var template = document.getElementById("userTemplate");
// Create a new user object
var user = {
name: "John Doe",
email: "johndoe@example.com"
};
// Clone the template content
var clone = document.importNode(template.content, true);
// Update the template content with user data
clone.querySelector("h2").textContent = user.name;
clone.querySelector("p").textContent = user.email;
// Append the cloned content to the document
document.body.appendChild(clone);
</script>
In the example above, we have a <template>
tag with an id of "userTemplate" that contains a simple user profile. We use JavaScript to clone the template content, update the user data, and append the cloned content to the document.
Main Attributes of the <template>
Tag:
Attribute | Description |
---|---|
id | Specifies a unique id for the template |
content | Contains the content of the template |
Overall, the <template>
tag is a powerful tool for creating reusable content templates in HTML and dynamically rendering them on a webpage using JavaScript.