You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Handlebars的#each遍历多数组并在表格展示数据

问题描述

我有如下三个数组:

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

以下是我的部分代码,这些数组嵌套在输入JSON对象中:

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);

这是我的模板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>

当前渲染结果:

BEFOREAFTER
Name
Gender

我需要在<td></td>中填入什么内容,才能得到如下渲染结果?

BEFOREAFTER
NameJasonJenny
GenderMaleFemale

解决方案

利用Handlebars循环中的@index获取当前遍历的索引值,结合上层作用域访问previous和current数组,就能取出对应位置的元素。修改后的模板代码如下:

<table>
  <thead>
   <tr>
     <th></th>
     <th>BEFORE</th>
     <th>AFTER</th>
   </tr>
  </thead>
  <tbody>
     {{#each header}}
      <tr>
        <td>{{this}}</td>
        <td>{{../previous[@index]}}</td>
        <td>{{../current[@index]}}</td>
      </tr>
     {{/each}}
  </tbody>
</table>

关键说明:

  • @index:返回当前循环的索引(从0开始计数)
  • ../:由于在each循环内部作用域指向当前header元素,通过../回到上层作用域,才能访问到input对象中的previous和current数组
  • previous[@index]/current[@index]:通过索引匹配数组对应位置的元素,实现与header行的一一对应

内容的提问来源于stack exchange,提问作者Anon_J

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 00:35:00