HTML template Tag

HTML template Tag

HTML <template> Tag



The <template> is used to store HTML code fragments, which can be cloned and inserted in an HTML document.
The content of the tag is hidden from users being stored on the client-side. It is inert until activated using JavaScript.
The browser processes the content of the <template> element while loading the page to ensure that the code is valid.
Templates can be placed anywhere inside of <head><body>, or <frameset> and can contain any type of content which is allowed in those elements.
The <template> tag is a new element in HTML 5.

Syntax

The <template> tag comes in pairs, the content is written between opening (<template>) and closing (</template>) tags.

Example

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <template id="myTemplate">
      <p>Template content</p>
    </template>
    <div id="normalContent">
      <p>First paragraph</p>
    </div>
    <!-- JavaScript function clones the template and adds it to the document. -->
    <button onclick="useTemplate();">Show content</button>
    <script>
      function useTemplate() {
      var myTemplate = document.getElementById('myTemplate');
          normalContent = document.getElementById('normalContent');
          clonedTemplate = myTemplate.content.cloneNode(true);
          normalContent.appendChild(clonedTemplate);
          }
    </script>
  </body>
</html>

Result

template example
The <template> tag supports the Global Attributes.

Reactions

Post a Comment

0 Comments

close