非常教程

HTML参考手册

标签 | Elements

template

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

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

虽然, 在加载页面的同时,解析器确实处理 <template>元素的内容,这样做只是确保这些内容是有效的; 然而,元素的内容不会被渲染。

内容类别

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附加了两个新的行:

规范

Specification

Status

Comment

HTML Living StandardThe definition of 'template element' in that specification.

Living Standard

HTML5The definition of 'template element' in that specification.

Recommendation

Initial definition

浏览器兼容性

Feature

Chrome

Edge

Firefox

Internet Explorer

Opera

Safari

Basic Support

26

13

22

No

15

7.1

Feature

Android

Chrome for Android

Edge mobile

Firefox for Android

IE mobile

Opera Android

iOS Safari

Basic Support

?

?

(Yes)

22

No

?

8

HTML

超文本标记语言,它通过标记符号来标记要显示的网页中的各个部分。网页文件本身是一种文本文件,通过在文本文件中添加标记符,可以告诉浏览器如何显示其中的内容(如:文字如何处理,画面如何安排,图片如何显示等)。浏览器按顺序阅读网页文件,然后根据标记符解释和显示其标记的内容,对书写出错的标记将不指出其错误,且不停止其解释执行过程,编制者只能通过显示效果来分析出错原因和出错部位。但需要注意的是,对于不同的浏览器,对同一标记符可能会有不完全相同的解释,因而可能会有不同的显示效果。