HTML 5标准中最新引入的template标签介绍

现在,W3C没闲着,2013年5月,新的标准中,又引入了新的标签template模板,具体
标准见:https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/templates/index.html#template-element
  下面综合进行小结下,供各位学习

   首先,服务端的模板是不少了,大家也用的不少,现在其实就是客户端的模板,先看例子:

  [code="java"]

1 function supportsTemplate() {2 return ‘content‘ in document.createElement(‘template‘);3 }4 5 if (supportsTemplate()) {6 //支持标签7 } else {}

  
//不支持
[/code]
  上面代码是监测浏览器是否支持这标签了。目前只有chrome 26以上才支持这个标签;

[code="java"]

<template id="hhhhold-template"> <img src="" alt="random hhhhold image"> <h3 class="title"></h3></template><script> var template = document.querySelector(#hhhhold-template); template.content.querySelector(img).src = http://hhhhold.com/350x200; template.content.querySelector(.title).textContent = Random image from hhhhold.com document.body.appendChild(template.content.cloneNode(true));</script>

 

[/code]

 template标签中,给出了模板id,其中这里定义了空的图片,因为这些都是在
 运行时动态指定的,
 例子中的<SCRIPT>部门,就是通过template.content.querySelector去动态指定
 填充模板的内容,记得最后要用:
    document.body.appendChild(template.content.cloneNode(true));才算激活模板;

<template>标签可以放置在<head>,<body>或者<frameset>当中,也可以放在象table,tr等标签中,比如
   [code="java"]

1 <table>2 <tr>3 <template id="cells-to-repeat">4 <td>some content</td>5 </template>6 </tr>7 </table>

[/code]

但模板暂时还不支持嵌套。
  再来个复杂点的例子:
   
  [code="java"]

 1 <button onclick="useIt()">Use me</button> 2 <div id="container"></div> 3 <script> 4 function useIt() { 5 var content = document.querySelector(template).content; 6  7 var span = content.querySelector(span); 8  span.textContent = parseInt(span.textContent) + 1; 9  document.querySelector(#container).appendChild(10  content.cloneNode(true));11  }12 </script>

 

1 <template>2 <div>Template used: <span>0</span></div>3 <script>alert(Thanks!)</script>4 </template>

[/code]
   点按钮,就会每次在模板中,不断显示template used:数字 (数字不断+1),
例子其实也很容易理解。
    

转载:https://my.oschina.net/jackyrong/blog/132763

 

 更详细的介绍可以参考:
http://www.html5rocks.com/en/tutorials/webcomponents/template/?redirect_from_locale=zh

相关文章