This is an archived snapshot of W3C's public bugzilla bug tracker, decommissioned in April 2019. Please see the home page for more details.
Specification: http://www.whatwg.org/specs/web-apps/current-work/multipage/scripting-1.html Multipage: http://www.whatwg.org/C#the-template-element Complete: http://www.whatwg.org/c#the-template-element Referrer: http://t.co/tLwpI6EdML Comment: Improve the <template> example Posted from: 78.20.174.76 by mathias@qiwi.be User agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1546.0 Safari/537.36
Currently the example says: <!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 in data) { 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> Using `for…in` to iterate over arrays in JavaScript is generally a bad idea, though. It doesn’t guarantee index order, and the loop not only iterates over all enumerable properties of the object itself, but also those the object inherits from its constructor’s prototype (properties closer to the object in the prototype chain override prototypes’ properties), which may lead to issues. To avoid confusing developers reading the spec, I would suggest using `Array#forEach` instead: <script> var template = document.querySelector('#row'); data.forEach(function(cat) { 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>
I'll just use a numeric for loop.
Checked in as WHATWG revision r8025. Check-in comment: make this example script more resilient http://html5.org/tools/web-apps-tracker?from=8024&to=8025