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

I have this HTML template and jsRender:

<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):

 var data = [{ name: 'Dan Wahlin', shirtColor: 'white'}, { name: 'John Papa', shirtColor: 'black'}, { name: 'Scott Guthrie', shirtColor: 'red'} ] ; $('#output').html($('#template').render(data));​ 

As you can see, this is an example from John Papa. That is, I changed it a little. But it does not work properly. The reason is that jsRender expects a root object in Json, as in John’s example, where {{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, Json is not returned with a root object. How can I make this work? Change Json format (and how to do it?)? or am I doing something wrong in my jsRender code?

Thanks in advance!

+4
source share
3 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. Since when rendering a template with an array object, it displays the same template n times.

+2
source

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 iterate over the array passed to the render method instead of a single element, as in Jesus' answer.

+6
source

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

0
source

All Articles