<template>
版本:HTML5
HTML<template>元素是一种用于保存客户端内容机制,该内容在加载页面时不会呈现,但随后可以在运行时使用JavaScript实例化。
浏览器支持
![]() | ![]() | ![]() | ![]() | ![]() |
Firefox、Opera、Chrome 和 Safari 浏览器都支持<template>标签。 | ||||
注意:Internet Explorer 浏览器不支持<template>标签。 | ||||
将模板视为一个可存储在文档中以便后续使用的内容片段。虽然解析器在加载页面时确实会处理<template>元素的内容,但这样做只是为了确保这些内容有效;但元素内容不会被渲染。
| Content categories | Metadata content,flow content,段落内容元素, script-supporting element |
|---|---|
| Permitted content | No restrictions |
| Tag omission | 不允许,开始标签和结束标签都不能省略。 |
| Permitted parents | <body>,<frameset>,<head>,<dl>and<colgroup>without aspanattribute |
| Permitted ARIA roles | None |
| DOM接口 | HTMLTemplateElement |
属性
此元素仅包含全局属性。
但,HTMLTemplateElement有个属性:content,这个属性是只读的DocumentFragment包含了模板所表示的DOM树。
示例
首先我们从示例的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片段的结构。
既然已经创建了表并定义了模板,我们使用JavaScript将行插入到表中,每一行都是以模板为基础构建的。
// 通过检查来测试浏览器是否支持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模板元素。
}
结果是原始的HTML表格,通过JavaScript添加了两行新内容:
标准
| Specification | Status | Comment |
|---|---|---|
| HTML Living Standard template element | Living Standard | |
| HTML5 template element | Recommendation | Initial definition |





