vortex
vortex

Reputation: 123

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

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

Upvotes: 0

Views: 179

Answers (1)

76484
76484

Reputation: 8993

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.

Upvotes: 1

Related Questions