How can I iterate over a JSON array in a jsRender template?

I have this HTML and jsRender template:

<div id="output"></div>

<script id="template" type="text/x-jsrender">
<ul>
    {{for}}
    <li>{{:name}} likes to wear {{:shirtColor}} shirts</li>
    {{/for}}        
</ul>
</script>​

and I have javascript (jQuery) like this:

var data = [{
    name: 'Dan Wahlin',
    shirtColor: 'white'},
{
    name: 'John Papa',
    shirtColor: 'black'},
{
    name: 'Scott Guthrie',
    shirtColor: 'red'}
]
;

$('#output').html($('#template').render(data));​

As some may see, this is an example from John Papa. That is, I have modified it at bit. But it doesnt work as it should. The reason is that the jsRender expect a root object in the Json, as in Johns example where the {{for}} is {{for people}} and the data object looks like this:

var data = { people: [{
    name: 'Dan Wahlin',
    shirtColor: 'white'},
{
    name: 'John Papa',
    shirtColor: 'black'},
{
    name: 'Scott Guthrie',
    shirtColor: 'red'}
]
}
;

In my ASP.NET MVC controller the Json returned is not with an root object. How can I make this to work? Change the Json format (and how do I do that?)? or do I do something wrong in my jsRender-code?

Thanks in advance!

Answers


Change the template to:

<ul id="output"></ul>
<script id="template" type="text/x-jsrender">
    <li>{{:name}} likes to wear {{:shirtColor}} shirts</li>
</script>​

Must work. Because when you render a template with a array object, he render n times the same template.


I had the same problem. The following should do the trick for you:

<script id="template" type="text/x-jsrender">
    <ul>
        {{for #data}}
            <li>{{>name}} likes to wear {{>shirtColor}} shirts</li>
        {{/for}}
    </ul>
</script>

This allows you to loop over the array passed into the render method instead of the individual item as in Jesus's answer.


change {{for}} to {{for people}}


Need Your Help

Transparent View with Android

java android layout view transparency

I try to have a bitmap moving over my android application. I m be able to have my bitmap behind my text view, but not over them.

Explanation of [].slice.call in javascript?

javascript arrays call slice

I stumbled onto this neat shortcut for converting a DOM NodeList into a regular array, but I must admit, I don't completely understand how it works: