概要
HTML 模板元素 <template> 是一种机制,允许包含加载页面时不渲染、但又可以随后通过 JavaScript 实例化的客户端内容。可以将模板视作为存储在页面上稍后使用的一小段内容。尽管不会渲染,但解析器会在加载页面的时候处理 <template> 元素中的内容来确保它是有效的。
- Content categories Metadata content, flow content, phrasing content, script-supporting element
- Permitted content Metadata content, flow content, any valid HTML content that is permitted to occur within the
<ol>,<dl>,<figure>,<ruby>,<object>,<video>,<audio>,<table>,<colgroup>,<thead>,<tbody>,<tfoot>,<tr>,<fieldset>,<select>,<details>elements and<menu>whosetypeattribute is in popup menu state. - Tag omission None, both the starting and ending tag are mandatory.
- Permitted parent elements
<body>,<frameset>,<head>and<colgroup>without aspanattribute - DOM interface
HTMLTemplateElement
属性
该元素包含 全局属性。
除此以外,还包含只读的 content 属性,通过它可以读取模板内容。一般来说,可以通过判断 content 属性是否存在来判断浏览器是否支持 <template> 元素。
示例
首先我们以 HTML 部分来作为示例的开始。
<table id="producttable">
<thead>
<tr>
<td>UPC_Code</td>
<td>Product_Name</td>
</tr>
</thead>
<tbody>
<!-- existing data could optionally be included here -->
</tbody>
</table>
<template id="productrow">
<tr>
<td class="record"></td>
<td></td>
</tr>
</template>
然后我们来看示例的 JavaScript 部分,它将 HTML 实例化。
// Test to see if the browser supports the HTML template element by checking
// for the presence of the template element's content attribute.
if ('content' in document.createElement('template')) {
// Instantiate the table with the existing HTML tbody and the row with the template
var t = document.querySelector('#productrow'),
td = t.content.querySelectorAll("td");
td[0].textContent = "1235646565";
td[1].textContent = "Stuff";
// Clone the new row and insert it into the table
var tb = document.getElementsByTagName("tbody");
var clone = document.importNode(t.content, true);
tb[0].appendChild(clone);
// Create a new row
td[0].textContent = "0384928528";
td[1].textContent = "Acme Kidney Beans";
// Clone the new row and insert it into the table
var clone2 = document.importNode(t.content, true);
tb[0].appendChild(clone2);
} else {
// Find another way to add the rows to the table because
// the HTML template element is not supported.
}
结果将是一个包含两个新行(由 JavaScript 生成)的 HTML 表格。
标准
| Specification | Status | Comment |
|---|---|---|
| WHATWG HTML Living Standard template element |
Living Standard | No change |
| HTML5 template element |
Recommendation | Initial definition |
浏览器兼容性
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
|---|---|---|---|---|---|
| Basic support | 26 | 22 (22) | Not supported | 15 | 7.1 |
| Feature | Android | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|
| Basic support | ? | ? | ? | ? | iOS 8 |
另请参阅
- Web 组件:
<content>,<decorator>,<element>,<shadow>