我正在尝试渲染一个带有一些标签和相应翻译的表格。 翻译是这样传递的:
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/