template element
If you don't know what an element is or how you must use it, I recommend you read the "HTML tags and attributes" tutorial that you can find in the HTML tutorials section.
Table of contents
Description
The template
element allows authors to create document fragments with a preset format that can be reused to display data through scripts. This element, new in HTML5, introduces to the standard the concept of template, widely used in other areas of software and programming.
For example, a template can be defined with all the structure of the row of a table
, but without the content of each cell. A script can later take this template, clone it and fill the cells with informtaion retrieved from a database. Once appended to the document, the data from the database will be rendered with the structure provided by the template.
By itself, a template
represents nothing and is completely ignored by supporting browsers. This element has been designed to work with scripts that clone its contents, add data and append the result to active documents, whenever needed.
Examples
In the following example, a template
is declared with a structure thought to display personal data about the students of an institution. Then, a button is provided to activate the script that clones this template and fills each span
with the information it has stored in a variable (could be the case that this information was loaded from an external server, for example). After that, the information now structured, is attached to the document and therefore displayed by the browser.
<div>
<template id="studenttemplate">
<p>
<b>Name</b>: <span></span><br>
<b>Gender</b>: <span></span><br>
<b>Age</b>: <span></span>
</p>
<hr>
</template>
</div>
<p><input id="loadbutton" type="button" value="Load record" onclick="loadRecord()"></p>
<script>
var studentsData = [{name: 'Marie Curie',
gender: 'Female',
age: '148'},
{name: 'Isaac Newton',
gender: 'Male',
age: '373'},
{name: 'Albert Einstein',
gender: 'Male',
age: '136'}];
currentPos = 0;
function loadRecord() {
var template = document.getElementById('studenttemplate'),
studentData = studentsData[currentPos],
clone = template.content.cloneNode(true),
fields = clone.querySelectorAll('span');
fields[0].textContent = studentData.name;
fields[1].textContent = studentData.gender;
fields[2].textContent = studentData.age;
template.parentNode.appendChild(clone);
currentPos++;
if (currentPos >= studentsData.length)
document.getElementById('loadbutton').style.display = 'none';
}
</script>
Name:
Gender:
Age:
Attributes
Global attributes
For information about global attributes refer to this list of global attributes in HTML5.
Events
Global events
For information about global events refer to this list of global events in HTML5.