Reputation: 43
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
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
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