template

<template>

HTML<template> 元素 是一种用于保存客户端内容的机制,该内容在页面加载时不被渲染,但可以在运行时使用JavaScript进行实例化。

可以将一个模板视为正在被存储以供随后在文档中使用的一个内容片段。

内容类别 Metadata content, flow content, phrasing content, script-supporting element
允许的内容无限制
标记遗漏没有,起始和结束标签都是强制性的。
允许的父母没有span属性的<body>,<frameset>,<head>,<dl>和<colgroup>
允许ARIA角色没有
DOM接口HTMLTemplateElement

属性

这个元素只包含全局属性。

例子

首先我们从示例的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片段的结构。

既然已经创建了表格并定义了模板,我们使用JavaScript将行插入到表格中,每一行都是以模板为基础构建的。

// 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.querySelector("tbody" var clone = document.importNode(t.content, true tb.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.appendChild(clone2 } else { // Find another way to add the rows to the table because // the HTML template element is not supported. }

结果是原始的HTML表格,通过JavaScript附加了两个新的行:

规范

SpecificationStatusComment
HTML Living StandardThe definition of 'template element' in that specification.Living Standard
HTML5The definition of 'template element' in that specification.RecommendationInitial definition

浏览器兼容性

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic Support261322No157.1

FeatureAndroidChrome for AndroidEdge mobileFirefox for AndroidIE mobileOpera AndroidiOS Safari
Basic Support??(Yes)22No?8