【问题标题】:iterate through an array less then specific number of times遍历数组少于特定次数
【发布时间】:2012-11-12 15:59:09
【问题描述】:

我使用 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 个用户,因此 Stan、Cartman 和 Kennie 不会出现。 如果我需要迭代所有内容,我会使用这样的东西:

<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 的情况下更改我的模板以进行迭代?

【问题讨论】:

  • limit results of each in handlebars.js 的可能重复项或至少第一部分是,第二部分应该是一个单独的问题。
  • 两个最常见的 Handlebars 答案归结为 (1) 编写自定义帮助程序和 (2) 预处理您的数据。不要害怕浏览 Handlebars 源代码,看看它是如何实现标准助手的,它们非常简单。

标签: handlebars.js client-templates


【解决方案1】:

好的,我想出了解决问题 2 的方法:

使用this解决问题

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

至于第一个问题,显然没有办法用handlebar.js原生地做到这一点,所以我正在考虑如何为此编写自己的Helper。

PS。感谢 mu is too short 显示第一部分的答案: limit results of each in handlebars.js

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-12
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多