How can I do this type of Array in Handlebars?

I'm trying to recreate the following loop in Handlebars.

JAVASCRIPT VERSION - SAMPLE CODEPEN https://codepen.io/Len/pen/PozvRrd

As you see, it creates every combination from 2 arrays. When I tried to convert the working JS code in handlebars as a helper, I get the error ..."Uncaught TypeError: Cannot read property 'forEach' of undefined."

I tried to find a working version of this in handlebars, I've found some things but did not find the same generated results as the code pen.

My questions are below....

1 - What kind of loop is this called, when you iterate over each and every combination as you see in the output?

2 - Can someone point me to a sample of this being done in Handlebars?

Heres the code in Javascript that I'm trying to convert to Handlbars. I have oral surgery tmrw, sorry if I am slow getting back. Thanks in advance!

let arrayOne = [
  1,2,3,4,5
]

let arrayTwo = [
  "a","b","c","d","e"
]

arrayOne.forEach(printArrayOne);

function printArrayOne(item, index){  
  arrayTwo.forEach((value) => {
    document.getElementById("demo").innerHTML += item + ' - ' + value + "<br>";
  });
}

// OUTPUT
1 - a
1 - b
1 - c
1 - d
1 - e
2 - a
2 - b
2 - c
2 - d
2 - e
3 - a
3 - b
3 - c
3 - d
3 - e
4 - a
4 - b
4 - c
4 - d
4 - e
5 - a
5 - b
5 - c
5 - d
5 - e

1 answer

  • answered 2020-11-25 08:47 Vadim P.

    It looks like the best way is to review approach and use computed data in handlebars template, but anyway, regarding to questions:

    1 - It looks like a nested loop

    2 - Using existing data structures it's possible to loop in the same way as in JavaScript:

    {{#each arrayOne}}
       {{#each ../arrayTwo}}
          {{../this}} - {{this}}<br>
       {{/each}}
    {{/each}}
    

    Access to iteration variables within nested block described here, in last paragraph of #each helper description.

    Example: https://jsfiddle.net/rh86gst0/