HTML <template> Tag

The <template> tag in HTML is a mechanism for holding HTML content that is meant to be used later by JavaScript. This tag allows you to define reusable blocks of markup that are not rendered by the browser when the page is initially loaded. Instead, the content inside a <template> is inert and invisible until it's activated via JavaScript. This is extremely useful for scenarios where you need to dynamically create or modify HTML content based on user interaction or data fetched from a server, without having to construct HTML strings within your JavaScript code.

HTML Template Tag: Reusable Content Blocks in HTML

Syntax

<template>
  <!-- HTML content goes here -->
</template>

Attributes

Attribute Value Description
None N/A The <template> tag does not have any specific attributes.

Example

<!DOCTYPE html>
<html>
<head>
  <title>HTML Template Example</title>
</head>
<body>

  <template id="myTemplate">
    <p>This is a template paragraph.</p>
    <button class="myButton">Click Me</button>
  </template>

  <div id="contentContainer">
    <!-- Content will be inserted here -->
  </div>

  <script>
    const template = document.getElementById('myTemplate');
    const container = document.getElementById('contentContainer');

    const clone = template.content.cloneNode(true);
    container.appendChild(clone);
  </script>

</body>
</html>

More Examples

Example 1: Simple Dynamic Content Injection

This example demonstrates how to inject multiple instances of a template into the DOM.

<!DOCTYPE html>
<html>
<head>
    <title>Multiple Template Instances</title>
</head>
<body>
    <template id="userTemplate">
        <div class="user">
            <h3>User</h3>
            <p>Name: <span class="userName"></span></p>
            <p>Age: <span class="userAge"></span></p>
        </div>
    </template>

    <div id="userContainer"></div>

    <script>
        const userTemplate = document.getElementById('userTemplate');
        const userContainer = document.getElementById('userContainer');

        const users = [
            { name: 'Alice', age: 30 },
            { name: 'Bob', age: 25 },
            { name: 'Charlie', age: 35 }
        ];

        users.forEach(user => {
            const clone = userTemplate.content.cloneNode(true);
            clone.querySelector('.userName').textContent = user.name;
            clone.querySelector('.userAge').textContent = user.age;
            userContainer.appendChild(clone);
        });
    </script>
</body>
</html>

Explanation:

  1. We have a <template> defined with an id "userTemplate". It holds the structure for a user profile.
  2. An array of user data called users is created.
  3. For each user object, a clone of template's content is created.
  4. The clone's placeholders are populated with data from the users array
  5. Each populated clone is then appended to the userContainer.

Example 2: Using Template with Event Listeners

This example demonstrates how to add event listeners to cloned elements.

<!DOCTYPE html>
<html>
<head>
    <title>Template with Event Listeners</title>
</head>
<body>
    <template id="itemTemplate">
        <li class="listItem">
            <span class="itemText"></span>
            <button class="deleteButton">Delete</button>
        </li>
    </template>

    <ul id="listContainer"></ul>

    <script>
        const itemTemplate = document.getElementById('itemTemplate');
        const listContainer = document.getElementById('listContainer');

        const items = ["Item 1", "Item 2", "Item 3"];

        items.forEach(itemText => {
            const clone = itemTemplate.content.cloneNode(true);
            const listItem = clone.querySelector('.listItem');
            listItem.querySelector('.itemText').textContent = itemText;
            const deleteButton = listItem.querySelector('.deleteButton');

            deleteButton.addEventListener('click', function() {
                listItem.remove();
            });

            listContainer.appendChild(clone);
        });
    </script>
</body>
</html>

Explanation:

  1. The template contains a list item structure with a delete button.
  2. For each item in the items array a clone is created
  3. An event listener is attached to the delete button.
  4. When the delete button is clicked, it removes its parent list item from the DOM.

Browser Support

The <template> tag is supported by all modern browsers:

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

Notes and Tips

  • Inert Content: The content inside a <template> is not rendered or interpreted by the browser initially. This means scripts inside a template will not execute, and images won't be loaded until the content is actively added to the DOM.
  • Cloning: You must use template.content.cloneNode(true) to get a usable copy of the template's content. Modifying the template's content directly will affect future clones.
  • Best Practices: Use the <template> tag to keep HTML content separate from JavaScript, enhancing code maintainability and readability.
  • Dynamic Content: Templates are particularly useful for creating lists, tables, or any dynamic content where the structure repeats with different data.
  • Performance: Cloning template content is generally more performant than creating HTML from strings, especially for complex structures, as the browser parses the HTML only once.
  • Accessibility: Content inside the template is inert and will not be read by screen readers until it is added to the DOM. Ensure that when you add it to the DOM, it's appropriately structured for accessibility.