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:
<template id="rowTemplate">
<tr>
<td class="record"></td>
<td></td>
<td></td>
</tr>
</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:
<table id="testTable">
<thead>
<tr>
<td>
ID
</td>
<td>
name
</td>
<td>
twitter
</td>
</tr>
</thead>
<tbody>
<!-- rows to be appended here -->
</tbody>
</table>
<!-- row template -->
<template id="rowTemplate">
<tr>
<td class="record"></td>
<td></td>
<td></td>
</tr>
</template>
Use the following to clone the new row and append it to the table in JavaScript:
// get tbody and row template
var t = document.querySelector("#testTable tbody"),
row = document.getElementById("rowTemplate");
// modify row data
var td = row.getElementsByTagName("td");
td[0].textContent = "1";
td[1].textContent = "Sunny";
td[2].textContent = "@sunny_delhi";
// clone row and insert into table
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!