Search code examples
htmlhandlebars.js

how to iterate multiple arrays by using handlebars and #each to display values in a table?


I have three arrays as follows.

['Name', 'Gender']
['Jason', 'Male']
['Jenny', 'Female']

The below is a part of the code I made and those arrays are nested in the input json obj:

let htmlFile = await fs.promises.readFile(templatePath, {
   encoding: "utf-8",
});

let input = {
   header: ['Name', 'Gender'],
   previous: ['Jason', 'Male'],
   current: ['Jenny', 'Female']
}

let template = handlebars.compile(htmlFile);

return template(input);

This is the template html:

<table>
  <thead>
   <tr>
     <th></th>
     <th>BEFORE</th>
     <th>AFTER</th>
   </tr>
  </thead>
  <tbody>
     {{#each header}}
      <tr>
        <td>{{this}}</td>
        <td></td>
        <td></td>
      </tr>
     {{/each}}
  </tbody>
</table>

This is the current result:

BEFORE AFTER
Name
Gender

What should I put inside of <td></td> to result in the below?

BEFORE AFTER
Name Jason Jenny
Gender Male Female

Solution

  • You would need to use the lookup built-in helper to lookup the value at the current @index on the previous object for the first column and the current object for the second.

    The code becomes:

    const template = Handlebars.compile(`
      <table>
        <thead>
         <tr>
           <th></th>
           <th>BEFORE</th>
           <th>AFTER</th>
         </tr>
        </thead>
        <tbody>
           {{#each header}}
            <tr>
              <td>{{this}}</td>
              <td>{{lookup ../previous @index}}</td>
              <td>{{lookup ../current @index}}</td>
            </tr>
           {{/each}}
        </tbody>
      </table>
    `);
    
    const input = {
      header: ['Name', 'Gender'],
      previous: ['Jason', 'Male'],
      current: ['Jenny', 'Female']
    };
    
    const output = template(input);
    
    document.body.innerHTML = output;
    <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js"></script>