【问题标题】:Handlebars - Access array by external key in a nested eachHandlebars - 通过嵌套的每个外部键访问数组
【发布时间】:2018-09-26 07:56:58
【问题描述】:

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

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元素具有相同索引的元素。

但车把似乎不像另一个问题所建议的那样喜欢 translations[this]translations.this

有好心人能就这件事给我建议吗? 提前感谢您的回复。祝你今天过得愉快! :)

【问题讨论】:

    标签: javascript handlebars.js each


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2019-06-13
      • 1970-01-01
      • 2020-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-03
      相关资源
      最近更新 更多