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

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

本文关键字:迭代 JSON 数组 jsRender      更新时间:2023-09-26

我有这个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>​

我有这样的javascript(jQuery):

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

正如一些人可能看到的,这是约翰·帕帕的一个例子。也就是说,我已经对其进行了一点修改。但它不能正常工作。原因是 jsRender 期望 JSON 中有一个根对象,就像在 Johns 示例中一样,其中 {{for}} 是 {{for people}},数据对象如下所示:

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

在我的 ASP.NET MVC 控制器中,返回的 Json 不带有根对象。我怎样才能使它工作?更改 Json 格式(我该怎么做?还是我在jsRender代码中做错了什么?

提前感谢!

我遇到了同样的问题。以下应该可以为您解决问题:

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

这允许您循环传递到 render 方法的数组,而不是像耶稣的答案那样循环单个项目。

将模板更改为:

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

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

change {{for}}

to {{for people}}