0
0
HtmlConceptBeginner · 3 min read

HTML Template Tag: What It Is and How to Use It

The <template> tag in HTML is a container for HTML content that is not rendered immediately on the page. It holds markup that can be cloned and inserted into the document later using JavaScript, allowing you to reuse HTML structures without showing them upfront.
⚙️

How It Works

The <template> tag acts like a hidden box that stores HTML code but does not display it on the page right away. Think of it as a blueprint or a cookie cutter: the content inside the template is kept safe and invisible until you decide to use it.

When you want to show or reuse the stored content, you use JavaScript to copy (clone) the template's content and place it somewhere visible on the page. This way, you avoid repeating the same HTML code multiple times and keep your page cleaner.

💻

Example

This example shows a template with a simple message. The JavaScript copies the template content and adds it to the page when the button is clicked.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Template Tag Example</title>
</head>
<body>
  <template id="myTemplate">
    <p>This is content inside the template.</p>
  </template>

  <button id="showContent">Show Template Content</button>
  <div id="container"></div>

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

    button.addEventListener('click', () => {
      const clone = template.content.cloneNode(true);
      container.appendChild(clone);
    });
  </script>
</body>
</html>
Output
A button labeled 'Show Template Content'. When clicked, the text 'This is content inside the template.' appears below the button.
🎯

When to Use

Use the <template> tag when you want to prepare HTML content that you will add to the page later, especially when the content repeats or changes dynamically. For example:

  • Adding multiple cards or list items dynamically without writing the HTML multiple times.
  • Creating UI components that appear after user actions like clicks or form submissions.
  • Improving page performance by loading content only when needed.

This helps keep your HTML clean and your JavaScript simpler.

Key Points

  • The <template> tag content is not shown on page load.
  • Content inside <template> is inert and not part of the DOM until cloned.
  • Use JavaScript to clone and insert template content dynamically.
  • Great for reusable and dynamic HTML structures.

Key Takeaways

The