You need to enable JavaScript to run this app. Handlebars嵌套each循环中如何获取同索引子数组字段值
优惠活动
大模型
产品
解决方案
定价
更多

Handlebars嵌套each循环中如何获取同索引子数组字段值

Handlebars 嵌套 each 循环取同索引字段的实现方法

核心实现逻辑

不需要编写自定义辅助方法,依靠 Handlebars 内置能力即可完成取值:

  • #each 块内置暴露的 @index 变量:代表当前循环项在数组中的数字索引(从0开始计数)
  • 路径回溯语法 ../:可以跳出当前嵌套循环的上下文,回到外层的变量作用域
  • 内置 lookup 助手:用于动态根据索引/键名从数组/对象中取值(Handlebars 模板不支持直接写 JS 方括号取数组元素的语法,必须通过该助手实现动态索引取值)

修正后的可运行模板代码

{{#each orders}}
    <form action="/edit/{{orderID}}" method="post">
        <label for="customerName">客户姓名</label>
        <input type="text" value="{{customerName}}">
        <hr>
        <p>商品列表:</p>
        {{#each productNames}}
            <label for="productNames">{{this}}</label>
            <!-- 取与当前商品名同索引的quantity值 -->
            <input value="{{lookup ../quantity @index}}" type="number" name="quantity[]"> 
        {{/each}}
    </form>
{{/each}}

原有代码的报错原因

之前取值失效主要是两个问题:

  1. 嵌套遍历 productNames 时,当前上下文已经切换为数组里的单条商品名字符串(比如 product1),这个上下文里不存在 quantity 属性,直接访问自然无法取值
  2. 原本的表单提交路径写的是 {{._id}},但传入的订单对象里的主键字段是 orderID,未修正会导致编辑请求的路由匹配错误

可选优化方案

如果可以调整传入页面的 orders 数据结构,更推荐把原本平行的三个商品相关数组合并为对象数组,从结构上消除跨索引取值的需求:

  • 优化后的数据结构示例:
[
 {
   orderID: '5f69df7fb852e822bc1524e8',
   customerName: 'John',
   products: [
     {
       id: '5f622bf4ee562b1d645ec09c',
       name: 'product1',
       quantity: '1'
     },
     {
       id: '5f639ce70facd65c5c8e135e',
       name: 'product2',
       quantity: '1'
     }
   ]
 }
]
  • 对应简化后的模板代码,无需做索引回溯,可读性和可维护性更强:
{{#each products}}
    <label for="productNames">{{this.name}}</label>
    <input value="{{this.quantity}}" type="number" name="quantity[]"> 
{{/each}}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.24 09:54:08