Javascript 如何在jsRender模板中迭代JSON数组?

Javascript 如何在jsRender模板中迭代JSON数组?,javascript,jsrender,Javascript,Jsrender,我有这个HTML和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&

我有这个HTML和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>​
正如一些人所看到的,这是约翰·帕帕的一个例子。也就是说,我对它进行了一些修改。但它并没有发挥应有的作用。原因是jsRender期望Json中有一个根对象,就像约翰的例子一样,{{for}}是{{{for people}},数据对象如下所示:

var data = [{
    name: 'Dan Wahlin',
    shirtColor: 'white'},
{
    name: 'John Papa',
    shirtColor: 'black'},
{
    name: 'Scott Guthrie',
    shirtColor: 'red'}
]
;

$('#output').html($('#template').render(data));​
var data = { people: [{
    name: 'Dan Wahlin',
    shirtColor: 'white'},
{
    name: 'John Papa',
    shirtColor: 'black'},
{
    name: 'Scott Guthrie',
    shirtColor: 'red'}
]
}
;
在我的ASP.NET MVC控制器中,返回的Json不是根对象。我怎样才能让它工作?更改Json格式(我该怎么做?)?还是我在jsRender代码中做错了什么


提前谢谢

将模板更改为:

<ul id="output"></ul>
<script id="template" type="text/x-jsrender">
    <li>{{:name}} likes to wear {{:shirtColor}} shirts</li>
</script>​
    • {{:name}喜欢穿{{:shirtColor}衬衫

必须工作。因为当你用数组对象渲染一个模板时,他渲染了n次相同的模板。

将{{for}}更改为{{for people}

我也遇到了同样的问题。以下内容可以帮您解决问题:

<script id="template" type="text/x-jsrender">
    <ul>
        {{for #data}}
            <li>{{>name}} likes to wear {{>shirtColor}} shirts</li>
        {{/for}}
    </ul>
</script>

    {{对于#数据}}
  • {{>name}}喜欢穿{{>shirtColor}衬衫
  • {{/for}}
这允许您在传递到渲染方法的数组上循环,而不是像Jesus的回答中那样循环单个项。

当您将“ASP.NET MVC 4”框架称为“MVC”时,就像将IE称为“internet”。(关于标签)