javascript - Handlebars - 通过嵌套的 each 中的外部键访问数组

标签 javascript handlebars.js each

我正在尝试渲染一个带有一些标签和相应翻译的表格。 翻译是这样传递的:

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"
      }
    ]
  },
];

我必须呈现的翻译必须通过像这样的简单数组进行过滤:

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

这是我呈现表格的方式:

<table class="table table-hover" style="background-color:white" id="tblKeys">
  <thead>
    <tr>
      <th>Action</th>
      <th>Status</th>
      <th>Brand</th>
      <th>Type</th>
      <th>Key</th>
      {{#each langArray}}
      <th>{{this}}</th>
      {{/each}}
    </tr>
  </thead>
  <tbody>
    {{#each keys}}
    <tr>
      <td><a href="/keys/{{id}}/edit" class=""><i class="fa fa-edit"></i></a></td>
      <td>{{label}}</td>
      {{#each ../langArray}}
        {{#if translations[this]}}
          <td>{{translations[this].text}}</td>
        {{else}}
          <td></td>
        {{/if}}  
      {{/each}}
    </tr>
    {{/each}}

  </tbody>
</table>

我的问题是,由于 langArray 用于设置表格标题,我需要为数据行遵守相同的顺序,而传入的数据 JSON 不能保证这一点。因此,我需要遍历 keys,然后遍历 langArray 并获取数据 JSON 中与当前 langArray 具有相同索引的元素> 元素。

但是 handlebars 似乎不喜欢 translations[this] 也不喜欢 translations.this as another question suggested.

有好心人能给我一些建议吗? 预先感谢您的答复。祝你今天过得愉快! :)

最佳答案

我通过对两个级别给出不同的引用然后使用双重查找解决了这个问题:

  <tbody>
    {{#if rows}}
      {{#each rows as |row|}}
        <tr>
          <td><a href="/keys/{{row.id}}/edit" class=""><i class="fa fa-edit"></i></a></td>
          <td>{{row.status}}</td>
          <td>{{row.brand}}</td>
          <td>{{row.type}}</td>
          <td>{{row.label}}</td>
          {{#each ../langArray as |lang|}}
            <td>{{lookup (lookup row.translations lang) 'text'}} </td>
          {{/each}}
        </tr>
      {{/each}}
    {{else}}  
      <tr><td colspan="100" class="text-center">There are no keys to show.</td></tr>
    {{/if}}
  </tbody>

希望这对其他人有帮助! :)

关于javascript - Handlebars - 通过嵌套的 each 中的外部键访问数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49859649/

相关文章:

javascript - 从字符串生成 JSON

javascript - 在 vuex + Firebase 应用程序中获取使用重定向方法登录的结果

jquery - 更改段落中随机字母的颜色

jquery - 为每个 jQuery 分组相同的值

javascript - jQuery Mobile 在另一个函数完成后执行一个函数

javascript - 从数组中随机选择唯一项目并添加到新数组的问题

javascript - 无法使用 Handlebars 在 View 目录中查找 View "error"

ember.js - Emberjs v0.9.7.1 的断言失败错误 - 如果您还指定了模板名称,则无法提供模板 block

javascript - 我如何在 Mustache.js 中实现这一目标?

javascript - jquery each 使用 "where clause"迭代复杂的 JSON 结构