【问题标题】:How can I iterate over a JSON array in a jsRender template?如何遍历 jsRender 模板中的 JSON 数组?
【发布时间】:2012-06-13 14:37:05
【问题描述】:

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

正如某些人所见,这是 John Papa 的一个例子。也就是说,我稍微修改了一下。但它不能正常工作。原因是 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 代码中做错了什么?

提前致谢!

【问题讨论】:

  • 当你调用"ASP.NET MVC 4"框架只是"MVC",就像把IE称为"互联网”。 (关于标签)

标签: javascript jsrender


【解决方案1】:

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

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

这使您可以循环传递给 render 方法的数组,而不是像耶稣回答中的单个项目。

【讨论】:

    【解决方案2】:

    将模板更改为:

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2020-12-03
        • 1970-01-01
        • 2020-01-12
        • 2017-08-13
        • 1970-01-01
        • 1970-01-01
        • 2015-03-16
        • 2018-10-05
        • 1970-01-01
        相关资源
        最近更新 更多