迭代数组少于特定次数

时间:2012-11-12 15:59:09

标签: handlebars.js client-templates

我使用Handlebars.js作为js模板。我需要迭代数组,但直到数组完成,但不到特定的次数。

假设我有以下JSON:

{
    "obj":
        [
            {"user": "Fred", "age": "23", "type": "personal"},
            {"user": "Ralph", "age": "32", "type": "business"},
            {"user": "John", "age": "44", "type": "other"},
            {"user": "Alex", "age": "44", "type": "other"},
            {"user": "Stan", "age": "6", "type": "other"},
            {"user": "Cartman", "age": "5", "type": "other"},
            {"user": "Kennie", "age": "6", "type": "other"}
        ]
}

但我只需要输出前4位用户,所以斯坦,卡特曼和肯尼不会在那里。 如果我需要迭代一切,我会使用这样的东西:

<ul>
    {{#each obj}}
    <li>
        <div>{{this.user}}</div>
        <div>{{this.age}}</div>
        <div>{{this.type}}</div>
    </li>
    {{/each}}
</ul>

我该如何修改?

问题2: 目前我只使用obj是因为我无法弄清楚如何迭代只包含数组的JSON:

        [
            {"user": "Fred", "age": "23", "type": "personal"},
            {"user": "Ralph", "age": "32", "type": "business"}
        ]

如果没有那个讨厌的obj,我怎样才能将模板更改为迭代?

1 个答案:

答案 0 :(得分:0)

好的,我找到了解决问题2的方法:

使用this解决问题

<ul>
    {{#each this}}
    <li>
        <div>{{this.user}}</div>
        <div>{{this.age}}</div>
        <div>{{this.type}}</div>
    </li>
    {{/each}}
</ul>

关于第一个问题,显然没有办法用handlebar.js本地做这个,所以我在想如何为此编写自己的助手。

PS。感谢 mu太短以显示第一部分的答案: limit results of each in handlebars.js