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

Handlebars:嵌套each中通过外部键访问数组的实现问题

在Handlebars中用嵌套each循环结合外部数组过滤翻译内容

刚好我之前处理过类似的Handlebars嵌套循环需求,来给你一步步解决这个问题!核心是要在嵌套循环里正确访问外部的langArray,并根据语言码匹配对应的翻译内容。

第一步:修正数据结构(重要!)

你提供的translations写成了数组[],但实际上它是键值对结构(语言码为键),应该改为对象{},否则无法通过语言码直接取值:

const keys = [
  { 
    id: 1, 
    label: "one", 
    translations: { 
      en: { text: "one" }, 
      it: { text: "uno" }, 
      es: { text: "uno" }, 
      fr: { text: "un" } 
    } 
  },
  { 
    id: 2, 
    label: "two", 
    translations: { 
      es: { text: "dos" }, 
      en: { text: "two" }, 
      it: null, 
      fr: { text: "deux" } 
    } 
  }
];

const langArray = ["en", "it", "es"];

第二步:Handlebars模板实现

这里用到@root访问顶层上下文,lookup内置助手根据键取值,with助手处理空值:

<table border="1" cellpadding="8">
  <!-- 生成表头:Label + 选中的语言码 -->
  <thead>
    <tr>
      <th>*Label*</th>
      {{#each @root.langArray}}
        <th>*{{this}}*</th>
      {{/each}}
    </tr>
  </thead>
  <tbody>
    <!-- 遍历每个标签项 -->
    {{#each keys}}
      <tr>
        <td>{{this.label}}</td>
        <!-- 遍历langArray,匹配对应翻译 -->
        {{#each @root.langArray}}
          {{!-- 用lookup助手:从上层的translations对象中,以当前语言码为键取值 --}}
          {{#with (lookup ../translations this)}}
            <td>{{this.text}}</td>
          {{else}}
            <td>-</td> {{!-- 无翻译时显示占位符 --}}
          {{/with}}
        {{/each}}
      </tr>
    {{/each}}
  </tbody>
</table>

关键知识点解释

  1. @root的作用:在嵌套的each循环中,@root指向最顶层的上下文,所以不管当前循环到哪一层,都能直接拿到langArray。
  2. lookup内置助手:语法是lookup 对象 键名,这里../translations表示上一层上下文(当前的标签项)的translations对象,this是当前遍历的语言码,两者结合就能精准获取对应翻译。
  3. with助手处理空值:如果某个语言的翻译是null或不存在,就会进入else分支显示占位符,避免页面出现空白或错误。

渲染后的效果

最终会生成这样的表格:

Labelenites
oneoneunouno
twotwo-dos

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:26:08