HTML template Tag
The HTML <template>
tag is used to declare HTML content that can be cloned and inserted into the document later using JavaScript. It provides a way to define reusable HTML templates that can be dynamically instantiated and customized.
Here’s an example of how the <template>
tag can be used:
<template id="myTemplate">
<h2>Template Content</h2>
<p>This is a reusable template.</p>
</template>
<div id="templateContainer"></div>
<script>
// Cloning and inserting the template content
const template = document.getElementById('myTemplate');
const templateContent = template.content.cloneNode(true);
document.getElementById('templateContainer').appendChild(templateContent);
</script>
In the above example, the <template>
tag defines a reusable template with some content inside it. The id
attribute is used to uniquely identify the template. The actual content of the template is enclosed within the <template>
opening and closing tags.
To use the template, JavaScript is used to clone the template content using the cloneNode(true)
method, which creates a deep copy of the content. The cloned content can then be inserted into the document wherever desired.
In this case, the cloned content is appended to the <div>
element with the id
“templateContainer”. The result is that the template content is inserted into the document, creating a new instance of the template.
The advantage of using <template>
is that it allows you to define complex HTML structures, including multiple elements and nested elements, as a template. This template can then be easily cloned and inserted into the document whenever needed, reducing code duplication and improving maintainability.
Furthermore, since the content inside the <template>
tag is inert, it does not get rendered by the browser until it is instantiated and inserted into the document. This can be useful for cases where you want to include HTML content but initially hide it or dynamically generate it based on certain conditions.
Overall, the <template>
tag provides a powerful mechanism for creating reusable HTML templates that can be dynamically instantiated and customized using JavaScript.