HTML - HTML Template Tag (<template>)

The <template> tag in HTML is used to store HTML content that should not be displayed immediately when the web page loads. The content inside the template remains hidden and is only shown when it is activated using JavaScript.

It acts like a blueprint or reusable structure that developers can use multiple times without rewriting the same HTML code.

Purpose of the <template> Tag

Normally, any HTML written inside the body is rendered by the browser instantly. However, sometimes developers want to prepare content in advance and display it later based on user interaction or program logic. The <template> element solves this problem.

It allows you to:

  • Keep reusable HTML structures ready.

  • Improve performance by avoiding repeated HTML creation.

  • Dynamically generate content using JavaScript.

Basic Syntax

<template id="cardTemplate">
  <div class="card">
    <h3>Title</h3>
    <p>Description</p>
  </div>
</template>

The content inside <template> will not appear on the webpage until JavaScript inserts it into the document.

How It Works

The browser stores template content separately from the main DOM. To use it, JavaScript must copy the template content and add it to the visible page.

Example:

<button onclick="showCard()">Show Card</button>

<div id="container"></div>

<template id="cardTemplate">
  <div class="card">
    <h3>Student Name</h3>
    <p>Course Information</p>
  </div>
</template>

<script>
function showCard() {
  let template = document.getElementById("cardTemplate");
  let clone = template.content.cloneNode(true);
  document.getElementById("container").appendChild(clone);
}
</script>

When the button is clicked, the template content becomes visible.

Key Features

  1. Content inside <template> is not rendered automatically.

  2. Scripts and styles inside the template do not execute until inserted into the DOM.

  3. It supports cloning, allowing multiple copies of the same structure.

  4. Helps separate HTML structure from JavaScript logic.

Advantages

  • Reduces duplicate HTML code.

  • Makes dynamic web applications easier to manage.

  • Improves code organization and maintainability.

  • Useful for modern frameworks and component-based development.

Common Use Cases

  • Creating reusable cards or list items.

  • Dynamic product listings.

  • Chat message layouts.

  • Popups and modal windows.

  • Data-driven UI generation.

Difference Between <template> and Hidden Elements

Using display:none only hides elements visually, but they still exist in the DOM. The <template> element keeps content completely inactive until needed, making it more efficient.

Conclusion

The <template> tag is an important modern HTML feature used to build dynamic and reusable user interfaces. It allows developers to prepare content structures in advance and display them only when required using JavaScript, resulting in cleaner and more efficient web development.