javascriptjsrenderjsviews

How can I iterate over an array of objects in JSRender?


I can only render the first object from an array of objects in JSRender. How can I iterate all of the objects?

{{for #data}} only shows first object from the data array.

var data = [{
    "id": "15",
    "name": "Jane Doe",
    "value": null
}, {
    "id": "6",
    "name": "John Smith",
    "value": "123-456-7890"
}, {
    "id": "6",
    "name": null,
    "value": "223-456-7890"
}]

Codepen: https://codepen.io/ryanmac/pen/ZEWQMNV

HTML:

<div id="result"></div>

<script id="theTmpl" type="text/x-jsrender">
  
<table><tbody>
{{for #data}}
  <tr><td><b>name:</b> {{:name}}</td><td>{{:value}}</td></tr>
{{/for}}
</tbody></table>

JS:

var data = [{
    "id": "15",
    "name": "Jane Doe",
    "value": null
}, {
    "id": "6",
    "name": "John Smith",
    "value": "123-456-7890"
}, {
    "id": "6",
    "name": null,
    "value": "223-456-7890"
}];
var template = $.templates("#theTmpl");

var htmlOutput = template.render(data);

$("#result").html(htmlOutput);

Output:

name: Jane Doe

Where did the other rows go? How can I debug this?


Solution

  • Its because you did not close the <script> tag

    <script id="theTmpl" type="text/x-jsrender">
     ....
    </script>