<template>: the "content template" element

The HTML <template> element is a mechanism for holding HTML that does not need to be displayed immediately when a page loads, but can be instantiated later during runtime using JavaScript.

Think of a template as a piece of content that is stored for later use in the document. Although the parser processes the contents of the <template> element as the page loads, it does so only to ensure that those contents are valid; however, the contents of the item are not displayed.

Examples

HTML

<table id="producttable">
  <thead>
    <tr>
      <td>UPC_Code</td>
      <td>Product-Name</td>
    </tr>
  </thead>
  <tbody>
    I dati potrebbero essere inclusi qui
  </tbody>

  <template id="productrow">
    <tr>
      <td class="record"></td>
      <td></td>    
    </tr>  
  </template>

First, we have a table into which we will later insert the content using JavaScript code. Then comes the template, which describes the structure of an HTML fragment representing a single table row.

Now that the table has been created and the model defined, we use JavaScript to insert rows into the table, with each row constructed using the model as a base.

if ('content' in document.createElement('template')) {
  var tbody = document.querySelector("tbody");
  var template = document.querySelector("#productrow");
  var clone = template.content.cloneNone(true);
  var td = clone.querySelectorAll("td");
  td[0].textContent = "1235646565";
  td[1].textContent = "Stuff";

  tbody.appendChild(clone);

  var clone2 = template.content.cloneNone(true);
  var td = clone2.querySelectorAll("td");
  td[0].textContent = "01538291283";
  td[1].textContent = "Other stuff";

  tbody.appendChild(clone2);
} else {
  //Trova un altro modo di aggiungere righe alla tabella
  // nel caso in cui template non è supportato
  
}