Search code examples
handlebars.jseach

Is there any way to nest 2 different object in handlebars with node js


I am trying to use each using handlebars for iterating over 2 objects of type array, when I iterate over them individually that works fine; but when there is a nesting of both inner object each isn't working.

a = [{a: "A"}, {a: "B"}, {a: "C"}]
b = [{b: "X"}, {b: "Y"}, {b: "Z"}]

Now these both objects can be iterated fine with

{{#each a}}
    {{this.a}}
{{/each}}
{{#each b}}
    {{this.b}}
{{/each}}

But it wont work for

{{#each a}}
    {{this.a}} //this is getting printed

    {{#each b}}
        {{this.b}} //this isn't getting printed
    {{/each}}
{{/each}}

(I've not mentioned any HTML syntax to reduce any confusions )


Solution

  • Your problem is that your data context is different when you are within the #each block. Within #each, your context is the current element in the iteration, { a: "A" }, { b: "B" }, etc. To access an object of the parent context you use Handlebars Paths:

    {{#each a}}
        {{this.a}}
        {{#each ../b}}
            {{this.b}}
        {{/each}}
    {{/each}}