Search code examples
javascriptjsrender

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!


Solution

  • 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.