Handlebars.js: index access to global.json from a loop

你。 提交于 2021-02-04 08:32:09

问题


I have a global.json file:

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

and I want the following result for A as an example:

A
B C

I tried to use the following handlebars script:

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

{{name}}

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

The output is is just A. However, it seems this is not recognized as integer here to used as the index


回答1:


You will need to use the lookup helper to lookup the dynamic this index on @root.global.dict. You would then have to do a second lookup to get the name property of the result. Alternatively, you could use the with helper to give you a block scoped to the result of the first lookup, as in:

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

I have created a fiddle for your reference.



来源:https://stackoverflow.com/questions/61763124/handlebars-js-index-access-to-global-json-from-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!