Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 285
user1453903 Avatar asked Feb 21 '23 04:02

user1453903


1 Answers

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.

like image 108
nfplee Avatar answered Apr 27 '23 18:04

nfplee