【问题标题】:Handlebars.js: index access to global.json from a loopHandlebars.js:从循环中对 global.json 的索引访问
【发布时间】:2020-05-13 21:21:02
【问题描述】:

我有一个 global.json 文件:

{
    "title": "problem",
    "dict": [
        {
            "name": "A",
            "similar": [1, 2]
        },
        {
            "name": "B",
            "similar": [0]
        },
        {
            "name": "C",
            "similar": [1]
        },
     ]
}

我希望以 A 的以下结果为例:

A
B C

我尝试使用以下车把脚本:

{{#with global.dict.[0]}}

{{name}}

{{#each similar}}
   {{@root.global.dict.[this].name}}
{{/each}}
{{/with}}

输出只是A。但是,似乎this 在这里没有被识别为整数来用作索引

【问题讨论】:

  • 每个similar 属性的值是否旨在成为dict 内的索引?如果是这样,例如,不应该是 [1, 2] 而不是 [2, 3] - 即,这些不应该是 0 索引吗?
  • @76484,你是对的。修复了示例中的索引。

标签: json handlebars.js


【解决方案1】:

您需要使用查找帮助程序来查找lookup @root.global.dict 上的动态this 索引。然后,您必须进行第二次查找才能获得结果的 name 属性。或者,您可以使用 with 助手为您提供一个范围为第一次查找结果的块,如下所示:

{{#each similar}}
    {{#with (lookup @root.global.dict this)}}
        {{name}}
    {{/with}}
{{/each}}

我创建了一个fiddle 供您参考。

【讨论】:

    猜你喜欢
    • 2013-03-16
    • 2021-04-07
    • 2023-03-05
    • 2021-09-08
    • 2012-11-18
    • 2018-02-10
    • 2013-01-29
    • 2021-09-21
    相关资源
    最近更新 更多