Template Tag in HTML5

Introduction

 
W3C has introduced a new "template" tag that provides a mechanism to define HTML markup fragments as prototypes. In practice, a template can be used to insert fragments of HTML code into your page, for example
  1. <template id="rowTemplate">  
  2. <tr>  
  3. <td class="record"></td>  
  4. <td></td>  
  5. <td></td>  
  6. </tr>  
  7. </template>  

Features

 
The following are the features of the template tag:
  • The template code can be defined nearly anywhere; the head, body or even a frameset.
  • Templates will not be displayed
  • Templates are not considered to be part of the document, in other words using document.getElementById(“mytablerow”) will not return child nodes.
  • Templates are inactive until used, in other words, enclosed images will not download, media will not play, scripts will not run, and so on.

Using templates

 
To use a template, it must be cloned and inserted into the DOM. For example, assuming the following HTML:
  1. <table id="testTable">  
  2.     <thead>  
  3.         <tr>  
  4.             <td>  
  5.                 ID  
  6.             </td>  
  7.             <td>  
  8.                 name  
  9.             </td>  
  10.             <td>  
  11.                 twitter  
  12.             </td>  
  13.         </tr>  
  14.     </thead>  
  15.     <tbody>  
  16.         <!-- rows to be appended here -->  
  17.     </tbody>  
  18. </table>  
  19. <!-- row template -->  
  20. <template id="rowTemplate">  
  21. <tr>  
  22. <td class="record"></td>  
  23. <td></td>  
  24. <td></td>  
  25. </tr>  
  26. </template>  
Use the following to clone the new row and append it to the table in JavaScript:
  1. // get tbody and row template  
  2. var t = document.querySelector("#testTable tbody"),  
  3.     row = document.getElementById("rowTemplate");  
  4. // modify row data  
  5. var td = row.getElementsByTagName("td");  
  6. td[0].textContent = "1";  
  7. td[1].textContent = "Sunny";  
  8. td[2].textContent = "@sunny_delhi";  
  9. // clone row and insert into table  
  10. t.appendChild(row.content.cloneNode(true)); 
Q: Can we use templates?
 
A: Not yet. For now, it’s supported in the latest version of Chrome and Firefox nightly builds but yes, there’s a shim demonstrated that you can use as a workaround until it is implemented by all prominent browsers. It probably works in IE also.
 
Shim DemoLink: jsfiddle
 
Separation of HTML code and JavaScript is a good idea!