html
  1. html-template-tag

HTML <template> Tag

  • The HTML <template> tag is used to declare fragments of HTML that can be cloned and inserted into the document by script.
  • It is a mechanism for holding client-side content that is not to be rendered when a page is loaded but can be instantiated at runtime.

Syntax

The <template> tag has the following syntax:

<template id="templateId">
  <!-- Fragment of HTML code goes here -->
</template>

Example

The following example shows how to use the <template> tag to declare a fragment of HTML code:

<!DOCTYPE html>
<html>
<head>
  <title>HTML template tag example</title>
</head>
<body>
  <template id="tpl">
    <h1>Template Example</h1>
    <p>This is an example of the template tag</p>
  </template>

  <script>
   var template = document.querySelector('#tpl');
   var clone = document.importNode(template.content, true);
   document.body.appendChild(clone);
  </script>
</body>
</html>
Try Playground

Explanation

The <template> tag consists of two parts:

  • An id attribute: This attribute is used to uniquely identify the template.
  • The template content: This is the fragment of HTML code that represents the template.

The content of a <template> element is not rendered by default - it remains inert until activated by a script. To clone and activate a template, the content needs to be imported into the main document using JavaScript.

Use

The main use of the <template> tag is to define reusable fragments of HTML code that can be dynamically inserted into a webpage. This can help to reduce duplication of code and simplify maintenance.

The <template> tag can be used to create custom elements and shadow DOM, which are powerful features for creating web components.

Important Points

The following are some important points to consider while using the <template> tag:

  • The content of a <template> tag is inert by default and needs to be cloned and activated using JavaScript.
  • The id attribute of the <template> tag is used to uniquely identify the template and should be unique within the document.
  • The content inside the <template> tag is not rendered, and cannot be accessed by CSS or JavaScript (until it is cloned and activated).
  • The <template> tag is a semantic tag that improves the structure and accessibility of an HTML document.

Summary

The HTML <template> tag is a powerful mechanism for declaring fragments of HTML code that can be dynamically inserted into a webpage. It helps to reduce duplication of code, simplify maintenance, and improve the structure and accessibility of an HTML document.

Published on: