HTML5 模板标签代码组织

HTML5 template tag code organization

是否最好将所有模板标签注入头部?

我认为这样代码会更清晰,它将元素拆分为可以呈现的项目和其他不能呈现的项目。 你觉得怎么样或者你自己用什么?

这确实是基于个人喜好和模板的上下文。 template 标签当然可以放在 head 元素中,因为 W3 standard allows metadata content there, and the template element can indeed be metadata. However, the W3 code example(转载如下)显示它放置在它打算使用的地方附近。

<!DOCTYPE html>
<title>Cat data</title>
<script>
 // Data is hard-coded here, but could come from the server
 var data = [
   { name: 'Pillar', color: 'Ticked Tabby', sex: 'Female (neutered)', legs: 3 },
   { name: 'Hedral', color: 'Tuxedo', sex: 'Male (neutered)', legs: 4 },
 ];
</script>
<table>
 <thead>
  <tr>
   <th>Name <th>Color <th>Sex <th>Legs
 <tbody>
  <template id="row">
   <tr><td><td><td><td>
  </template>
</table>
<script>
 var template = document.querySelector('#row');
 for (var i = 0; i < data.length; i += 1) {
   var cat = data[i];
   var clone = template.content.cloneNode(true);
   var cells = clone.querySelectorAll('td');
   cells[0].textContent = cat.name;
   cells[1].textContent = cat.color;
   cells[2].textContent = cat.sex;
   cells[3].textContent = cat.legs;
   template.parentNode.appendChild(clone);
 }
</script>