HTML template Tag: How it Works with Examples

html template tag

The HTML <template> tag lets you store HTML content that won’t show up right away. JavaScript can pull it in and display it when needed.

What is the <template> Tag in HTML?

The <template> tag in HTML holds client-side content that does not render when the page loads. It’s a way to save reusable HTML you can add later with JavaScript.

Here is the basic tag:

<template>
  <!-- inert HTML content -->
</template>

Anything inside <template> won’t show up on the page right away. The browser keeps it in memory as a special fragment, not the live page.

This means:

  • The content remains inactive.
  • It doesn’t interfere with page layout or scripts.
  • You can copy it and insert it whenever you need.

A <template> can hold any valid HTML. That includes <script> and <style>, but those elements stay inactive until added to the DOM.

  • You still need to follow the normal rules for how HTML elements nest.
  • Make sure the HTML is written properly so it works as expected.

Here is a quick example:

<template id="user-card">
  <div class="user">
    <h2></h2>
    <p></p>
  </div>
</template>

Scripts inside a template won’t run unless you insert them into the page. So, styles inside a template don’t affect the rest of the page.

<template>
  <style>
    .hidden { display: none; }
  </style>
  <script>
    console.log('This won\'t run');
  </script>
</template>

Here’s what makes it different from regular HTML elements:

  • Not Rendered: <template> does not render content.
  • Used for Reuse: Content is designed to be cloned and reused via JavaScript.
  • DocumentFragment: Template contents live in memory until explicitly inserted into the DOM.
  • Inert Scripts: Scripts don’t execute unless cloned and inserted manually.

Why Use the <template> Tag in HTML:

  • It lets you keep HTML out of the way until you need it.
  • It helps you to keep your HTML clean and simple.
  • <template> is useful when you create reusable UI components.
  • It supports dynamic content, which allows you to render it with JavaScript frameworks or vanilla DOM methods

How to Use the HTML <template> Tag with JavaScript

First, get the template by its ID or a CSS selector.

const template = document.querySelector('#my-template');

You can clone template content with document.importNode():

const clone = document.importNode(template.content, true);

The true means it copies everything inside it, not just the top level. You can insert the cloned node anywhere in your DOM:

document.body.appendChild(clone);

This method allows UI updates and renders modular content.

Browser Support

All modern browsers support the <template> tag:

  • Chrome 26+
  • Firefox 22+
  • Safari 7.1+
  • Edge 13+
  • Opera 15+

IE 11 does not support <template> natively.

Examples of HTML <template> Tag

Render a predefined card on button click

<template id="card-template">
  <div class="card">
    <h3>Card Title</h3>
    <p>You can use this card again.</p>
  </div>
</template>
<button onclick="addCard()">Add Card</button>
<div id="container"></div>

<script>
function addCard() {
  const tmpl = document.getElementById('card-template');
  const clone = document.importNode(tmpl.content, true);
  document.getElementById('container').appendChild(clone);
}
</script>

A card is cloned from a template and added to the container only when the button is clicked.

Populate user data from JSON with the template

<template id="user-template">
  <li>
    <strong class="name"></strong>: <span class="email"></span>
  </li>
</template>
<ul id="user-list"></ul>

<script>
const users = [
  { name: 'David', email: '[email protected]' },
  { name: 'Alaba', email: '[email protected]' }
];
const tmpl = document.getElementById('user-template');
const list = document.getElementById('user-list');

users.forEach(user => {
  const clone = document.importNode(tmpl.content, true);
  clone.querySelector('.name').textContent = user.name;
  clone.querySelector('.email').textContent = user.email;
  list.appendChild(clone);
});
</script>

Loops through user data and fills in template placeholders. Each user appears as a list item. That keeps the HTML more dynamic.

Create nested components within multiple templates

<template id="profile-template">
  <div class="profile">
    <h2 class="username"></h2>
    <div class="bio"></div>
  </div>
</template>
<template id="bio-template">
  <p>She likes JavaScript and HTML templates!</p>
</template>
<div id="profiles"></div>

<script>
const user = { name: 'Celina Developer' };
const profileTmpl = document.getElementById('profile-template');
const bioTmpl = document.getElementById('bio-template');

const profileClone = document.importNode(profileTmpl.content, true);
profileClone.querySelector('.username').textContent = user.name;

const bioClone = document.importNode(bioTmpl.content, true);
profileClone.querySelector('.bio').appendChild(bioClone);

document.getElementById('profiles').appendChild(profileClone);
</script>

This example shows how to nest templates for modular and component-like design.

Show the message only under a specific condition

<template id="message-template">
  <div class="alert">Welcome back, admin!</div>
</template>
<div id="messages"></div>

<script>
const userRole = 'admin';
if (userRole === 'admin') {
  const tmpl = document.getElementById('message-template');
  const clone = document.importNode(tmpl.content, true);
  document.getElementById('messages').appendChild(clone);
}
</script>

The template content only appears based on a condition.

Wrapping Up

In this article, you learned how the <template> tag works and why it’s useful. Also, you saw how to use it with JavaScript and how it fits into modern web development.

Here’s a quick recap:

  • <template> holds HTML that’s inert until used.
  • It helps reduce DOM clutter and supports reusable UI components.
  • You can clone and insert content with importNode().
  • It’s supported in all modern browsers, but not IE11.
  • Templates work great with loops and conditions. They also work with JSON-driven interfaces.

FAQs

What is the purpose of the <template> tag in HTML?

The <template> tag lets you store HTML code that stays inactive until triggered by JavaScript. It helps build UI pieces without rendering them on page load. Example:
<template id="card">
  <div class="card">Content</div>
</template>

How do you use the <template> tag with JavaScript?

You can select the template, clone its content, and insert it into the DOM using JavaScript. Example:
const tpl = document.getElementById("card");
const clone = tpl.content.cloneNode(true);
document.body.appendChild(clone);

Does the <template> tag improve page performance?

Yes. Since <template> content does not load or render at first, it reduces initial DOM size and speeds up load time.

Can search engines index content inside the <template> tag?

No. Search engines ignore <template> content because it does not render by default. Use real DOM insertion to expose important data for crawling.

Similar Reads

HTML style Tag: Inline CSS

The style tag in HTML defines CSS inside a web page. Click to see how it works with syntax and…

HTML embed Tag: How to Embed External Media in Web Pages

The HTML embed tag is used to display media content, such as videos or audio. It can also display PDFs…

HTML <cite> Tag: How to Reference Sources

The HTML <cite> tag is a small but important tool for marking up the title of a creative work. You…

HTML progress Tag: How to Create Progress Bars with Examples

The <progress> tag in HTML shows task completion. It gives users visual feedback as the task runs. Understand the <progress>…

HTML time Tag: Representing Dates and Times

The HTML time Tag marks time values in a document. Use it to show dates or times that machines and…

HTML pre Tag: How to Display Preformatted Text

The HTML <pre> tag keeps the original format of your text. It shows spaces and line breaks exactly as you…

The Img Tag in HTML: How to Display Images

You need images to show products or ideas on your site. The HTML img tag places those images on the…

HTML Heading Elements: Understanding h1 to h6 with Examples

The heading elements define a content structure in HTML. Use <h1> to <h6> to show levels. <h1> means the main…

HTML data Tag: Machine-Readable Data

The data tag connects visible content with a machine-readable value in HTML. This helps browsers and tools understand and process…

HTML base Tag: How to Set a Base URL for Links and Resources

Use the <base> tag in HTML to set a single base URL or target for all relative links and resources…

Previous Article

HTML meter Tag: Measurements with Examples

Next Article

HTML output Tag: How to Display Calculation Results

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.