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 不允许,开始标签和结束标签都不能省略。
- 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>
<!-- 现有数据可以可选地包括在这里 -->
</tbody>
</table>
<template id="productrow">
<tr>
<td class="record"></td>
<td></td>
</tr>
</template>
然后我们来看示例的 JavaScript 部分,它将 HTML 实例化。
// 通过检查来测试浏览器是否支持HTML模板元素
// 用于保存模板元素的内容属性。
if ('content' in document.createElement('template')) {
// 使用现有的HTML tbody实例化表和该行与模板
let t = document.querySelector('#productrow'),
td = t.content.querySelectorAll("td");
td[0].textContent = "1235646565";
td[1].textContent = "Stuff";
// 克隆新行并将其插入表中
let tb = document.getElementsByTagName("tbody");
let clone = document.importNode(t.content, true);
tb[0].appendChild(clone);
// 创建一个新行
td[0].textContent = "0384928528";
td[1].textContent = "Acme Kidney Beans";
// 克隆新行并将其插入表中
let clone2 = document.importNode(t.content, true);
tb[0].appendChild(clone2);
} else {
// 找到另一种方法来添加行到表,因为不支持HTML模板元素。
}
结果将是一个包含两个新行(由 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) | 未实现 | 15 | 7.1 |
| Feature | Android | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|
| Basic support | ? | ? | ? | ? | iOS 8 |
另请参阅
- Web 组件:
<content> -
<decorator>, <element>, {- {HTMLElement("shadow")}}