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 HTML5.

Everything within the <template> element is parsed like regular HTML. However, there are some exceptions:

  • It doesn't get rendered.
  • The <script> tags within it don't get run.
  • The <style> tags within it don't get evaluated.
  • External resources are not rendered.
  • Content within this element is not considered to be in the document. If the document.getElementById() or querySelector() is used in the main page, the child nodes of a template won't be turned back.

Syntax

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

Example of the HTML <template> tag:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <h1>This is a heading.</h1>
    <p>
     <q>If you tell the truth, you don't have to remember anything.</q>
      ― Mark Twain
    </p>
    <template>
      <h2>This is a second heading.</h2>
      <p>
        “I'm selfish, impatient and a little insecure. I make mistakes, I am out of control and at times hard to handle. But if you can't handle me at my worst, then you sure as hell don't deserve me at my best.”
        ― Marilyn Monroe
      </p>
    </template>
  </body>
</html>

Example of the HTML <template> tag used with JavaScript:

<!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

The <template> tag supports the Global Attributes.


Browser support

26+ 22+ 8+ 15+


Do you find this helpful?

Related articles