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

如何在Handlebars嵌套循环中获取外层循环的索引值?

在Handlebars中获取外层循环索引的解决方案

Handlebars里要获取外层循环的索引,主要靠上下文层级引用或者命名参数显式保存两种方式,针对你的三层循环场景,具体解决方法如下:

方法1:通过../层级引用索引

Handlebars中../用于访问父级上下文的变量,循环的@index也适用这个规则:

  • 第三层productDetails循环中,要拿中间层orders的索引用../@index
  • 要拿最外层orderList的索引用../../@index

修改你代码里的changeStatus调用部分,把对应外层索引传进去:

{{#each orderList}}
    {{#each this.orders}}
        {{#each this.productDetails}}
            <td>{{../this.date}}</td>
            <td>{{this.name}}</td>
            <td>{{this.price}}</td>
            <td>{{this.quantity}}</td>
            <td>{{../this.billingAddress.address}}</td>
            <td>{{../this.billingAddress.contact}}</td>
            <td>{{../this.paymentMode}}</td>
            <td class="text-center">
                {{#if this.status}}
                    <!-- 按需调整参数:第一个是最外层orderList索引,第二个是中间层orders索引 -->
                    <select onchange="changeStatus({{../../@index}},{{../@index}});" id="statusBox"> 
                    <option value="Placed">Placed</option>
                    <option value="Shipped">Shipped</option>
                    <option value="Cancel">Cancel</option>
                    </select>
                {{else}}
                    Canceled
                {{/if}}
            </td>
            <td>{{this.status}}</td>
        {{/each}}
    {{/each}}
{{/each}}

方法2:用命名参数显式保存索引(更直观)

如果觉得层级引用容易搞混,可以在each循环时给索引起个名字,后续直接用变量名调用,可读性更高:

{{#each orderList as |order orderIndex|}}
    {{#each order.orders as |orderItem orderItemIndex|}}
        {{#each orderItem.productDetails as |product productIndex|}}
            <td>{{orderItem.date}}</td>
            <td>{{product.name}}</td>
            <td>{{product.price}}</td>
            <td>{{product.quantity}}</td>
            <td>{{orderItem.billingAddress.address}}</td>
            <td>{{orderItem.billingAddress.contact}}</td>
            <td>{{orderItem.paymentMode}}</td>
            <td class="text-center">
                {{#if product.status}}
                    <select onchange="changeStatus({{orderIndex}},{{orderItemIndex}});" id="statusBox"> 
                    <option value="Placed">Placed</option>
                    <option value="Shipped">Shipped</option>
                    <option value="Cancel">Cancel</option>
                    </select>
                {{else}}
                    Canceled
                {{/if}}
            </td>
            <td>{{product.status}}</td>
        {{/each}}
    {{/each}}
{{/each}}

内容的提问来源于stack exchange,提问作者Muhammed Sibly B

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 16:45:42