HTML Tutorial

HTML Tag: <template>

Usage of <template>

The <template> tag is used to define a fragment of HTML that will not be rendered immediately in the browser. It can be used to:

  • Define reusable HTML components
  • Store HTML that will be added to the document later

Attributes of <template>

The <template> tag has no attributes.

Examples with <template>

1. Defining a Reusable Component

<template id="my-component">
  <div>
    <h1>My Component</h1>
    <p>This is a reusable component.</p>
  </div>
</template>

You can then use the component in your HTML by referencing its ID:

<my-component></my-component>

2. Storing HTML to Add Later

<template id="my-data">
  <table>
    <thead>
      <tr>
        <th>Name</th>
        <th>Age</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>John Doe</td>
        <td>30</td>
      </tr>
    </tbody>
  </table>
</template>

You can then add the data to your document later using JavaScript:

const template = document.getElementById('my-data');
document.body.appendChild(template.content);

Exploring the <template> Tag: A Simple HTML Example

<!DOCTYPE html>
<html>
<head>
  <title>Exploring the <template> Tag</title>
</head>
<body>
  <template id="my-template">
    <h1>Hello World</h1>
  </template>

  <script>
    // Get the template element
    const template = document.getElementById('my-template');

    // Clone the template content
    const clone = template.content.cloneNode(true);

    // Append the cloned content to the body
    document.body.appendChild(clone);
  </script>
</body>
</html>

In this example, the <template> tag is used to define a template with an "Hello World" heading. The JavaScript then clones the template content and appends it to the document body, effectively displaying the heading on the page.