HTML <template> 元素是用作保存用戶端內容的機制。該內容在頁面載入時不受渲染,但可以在運行時使用 JavaScript 實例化。
你可以把 template 想成文件裡面,被儲存以待稍後使用的內容片段。在頁面載入時,解析器雖然會處理 <template> 元件的內容,但元素本身並不會被渲染。
| 內容類型 | 元內容、流內容、phrasing content、支援腳本的元素 |
|---|---|
| 允許內容 | 沒有限制 |
| 標籤省略 | None, both the starting and ending tag are mandatory. |
| 允許的父元素 | <body>, <frameset>, <head>, <dl> and <colgroup> without a span attribute |
| 允許的 ARIA roles | 無 |
| DOM 介面 | HTMLTemplateElement |
屬性
本元素只允許全域屬性。
示例
我們先從 HTML 部分開始。
<table id="producttable">
<thead>
<tr>
<td>UPC_Code</td>
<td>Product_Name</td>
</tr>
</thead>
<tbody>
<!-- 在這裡可以選擇性地包括既有資料 -->
</tbody>
</table>
<template id="productrow">
<tr>
<td class="record"></td>
<td></td>
</tr>
</template>
首先,我們有個稍後將透過 JavaScript 插入的表格。接著,我們把重點轉移到描述 HTML 內容模板結構的 template:它意味著一個表格的行。
現在表格已經建立、也定義了模板,所以我們將以 template 為基礎,用 JavaScript 把每個產生出來的行加到表格內。
// 透過檢查 HTML template 元素屬性的存在與否,以測試瀏覽器是否支援它
if ('content' in document.createElement('template')) {
// 使用現有 HTML tbody、行以及模板,來實例化表格
var t = document.querySelector('#productrow'),
td = t.content.querySelectorAll("td");
td[0].textContent = "1235646565";
td[1].textContent = "Stuff";
// 複製新的行並將其插至表格
var tb = document.querySelector("tbody");
var clone = document.importNode(t.content, true);
tb.appendChild(clone);
// 複製新的行
td[0].textContent = "0384928528";
td[1].textContent = "Acme Kidney Beans";
// 複製新的行並將其插至表格
var clone2 = document.importNode(t.content, true);
tb.appendChild(clone2);
} else {
// 因為 HTML template 不被支援,所以要用其他方法在表格增加新行
}
結果會變成原生的 HTML 表格,它透過 JavaScript 產生了兩個新行:
table {
background: #000;
}
table td {
background: #fff;
}
規範
| 規範 | 狀態 | 註解 |
|---|---|---|
| HTML Living Standard The definition of 'template element' in that specification. |
Living Standard | |
| HTML5 The definition of 'template element' in that specification. |
Recommendation | 初始定義 |
瀏覽器相容性
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
| Feature | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|---|
| Basic support | 26 | 13 | 22 | No | 15 | 8 |
| Feature | Android webview | Chrome for Android | Edge mobile | Firefox for Android | Opera Android | iOS Safari | Samsung Internet |
|---|---|---|---|---|---|---|---|
| Basic support | ? | ? | Yes | 22 | ? | 8 | ? |