The <template>
tag serves as a container with HTML
content that can be cloned multiple times and placed into the page with JavaScript.
The template itself is not visible.
The <template>
content is only visible after it has been cloned and added to the page.
A <template>
element that contains a dropdown control.
<template>
Approval Status:
<select>
<option value="">-- Select Status --</option>
<option value="pending">Pending</option>
<option value="approved">Approved</option>
<option value="rejected">Rejected</option>
</select>
</template>
A <template>
is a container of HTML elements that can be cloned by JavaScript.
Once cloned, it can be placed anywhere on the page.
The main purpose of this element is to allow reuse of HTML elements with great performance.
An example where a template is helpful is adding new rows to a table (see below).
A <template>
that contains a table row with three blank input fields.
Each time the 'Add Row' button is clicked a template input row is cloned and added to the table -- up to a maximum of 6 rows.
This design allows for rapid data entry of new user records.
First Name | Last Name | |
---|---|---|
<table id="user-table">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
<tr>
<td><input type="textbox" name="firstname" value="Anna"></td>
<td><input type="textbox" name="lastname" value="Kroger"></td>
<td><input type="textbox" name="emailname" value="anna@kroger.com"></td>
</tr>
</table>
<button onclick="addRow()">Add Row</button>
<template id="user-row">
<tr>
<td><input type="textbox" name="firstname"></td>
<td><input type="textbox" name="lastname"></td>
<td><input type="textbox" name="emailname"></td>
</tr>
</template>
<script>
let counter = 0;
let addRow = () => {
if (++counter > 6) {
alert("Max rows reached");
return;
}
let template = document.getElementById("user-row");
let newRow = template.content.cloneNode(true);
let table = document.getElementById("user-table");
table.appendChild(newRow);
}
</script>
Note: This example is not entirely complete. In a real-world solution the textboxes need to be assigned a unique name when added to the table.
The <template>
element has no attributes, but it does accept global attributes.
Below are attributes that JavaScript may use to locate <template>
elements.
Attribute | Value | Description |
---|---|---|
id | identifier | Defines a unique identifier for the template. |
class | classnames | Assigns a CSS class to the template. Use this class for JavaScript selection only. |
For additional global attributes see our global attributes list.
Note: CSS class names are often used by JavaScript to quickly locate multiple elements.
A common convention is to prefix these classes with 'js-' to indicate they are not used for styling.
Here is when <template>
support started for each browser:
Chrome
|
26.0 | Mar 2013 |
Firefox
|
22.0 | Jun 2013 |
IE/Edge
|
13.0 | Nov 2015 |
Opera
|
15.0 | Jul 2015 |
Safari
|
9.0 | Sep 2015 |