Sahyog Vishwakarma
Sahyog Vishwakarma

Reputation: 410

How to access data inside nested loop in Handlebars?

I have data as follows where keyPairs is dynamic columns of a table and data has the row data.

keyPairs: {
"key0":"Value0",
"key1":"Value1",
    ...
}

data:[
{
"name":"name0",
"key0":"Value0",
"key1":"---",
},

{
"name":"name1",
"key0":"---",
"key1":"Value1",
}]

The keyPairs object is dynamically created, and the keys used in each object in the data array are the same as the keys in keyPairs. I am unable get the values for each data item with each @key from keyPairs.

{{#each data as | row |}}
    <td>
        {{row.name}}
    </td>

{{#each ../keyPairs}}
    <td>
        {{./row[@key]}}
    </td>
{{/each}}
{{/each}}

Upvotes: 0

Views: 1012

Answers (2)

Sahyog Vishwakarma
Sahyog Vishwakarma

Reputation: 410

First of all, Thanks @76484 for your answer. Second I had got my answer on my own, and its quite similar to answer given by him. I achieved the solution to my question with the following syntax.

{{#each data as | row |}}
    <td>
        {{row.name}}
    </td>

{{#each ../keyPairs}}
    <td>
        {{lookup row @key}}
    </td>
{{/each}}
{{/each}}

Upvotes: 0

76484
76484

Reputation: 8993

I see a few problems.

First, you are trying to step-up a context-level from within your #each using ./row. However, the correct syntax for this is two dots, ../row.

Secondly, when you step-up a context-level, by using ../row you are trying to access a row property on the parent context. But the parent does not have a row property because the parent is the row object. So the correct reference would be .. instead of ../row.

Third, Handlebars does not support dynamic key evaluation with square brackets. You need to use the lookup helper to do this evaluation, {{lookup .. @key}}.

I have created a fiddle for your reference.

Upvotes: 1

Related Questions