user1453903
user1453903

Reputation: 43

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!

Upvotes: 4

Views: 6425

Answers (3)

nfplee
nfplee

Reputation: 7977

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.

Upvotes: 6

ComeIn
ComeIn

Reputation: 1609

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

Upvotes: 0

Jes&#250;s Quintana
Jes&#250;s Quintana

Reputation: 1813

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.

Upvotes: 2

Related Questions