htmltemplatetag

HTML5 template tag code organization


Is is best to inject all the template tags inside the head ?

I think this way the code will be much cleaner, which splits elements between items that can be rendered and others that not. What do you think or what do you use yourself ?


Solution

  • It really is based on personal preference and the context of the templates. The template tag can certainly be placed with in the head element, as the W3 standard allows metadata content there, and the template element can indeed be metadata. However, the W3 code example (reproduced below) shows it placed near where it is intended to be used.

    <!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>