如何在 Handlebars 中使用另一个变量指定对象键

How do I specify an objects key with another variable in Handlebars

我试图从 Ember 模板中使用变量作为键来获取对象值。我该怎么做?

我试过以下方法:

<table>
    {{#each record in model}}
    <tr>
        {{#each col in table.cols}}
            <td>{{record[col.field]}}</td>
        {{/each}}
    </tr>
    {{/each}}
</table>

变量:

var table = {           
   cols: [{
        header: 'Date/Time',
        field: 'date'
    },{
        header: 'Address',
        field: 'address'
    },{
        header: 'Type',
        field: 'type'
    }]
};

var model = [{
    id: 1,
    date: '8/18/85',
    address: '123 abc st',
    type: 'Unique'
}, {
    id: 2,
    date: '9/8/95',
    address: '123 abc st',
    type:'Foreign'
}]

构建时出现以下错误

Parse error on line 25: ...} {{record[col.field]}} ----------------------^ Expecting 'STRING', 'NUMBER', 'ID', 'DATA', got 'INVALID' Error: Parse error on line 25: ...} {{record[col.field]}} ----------------------^ Expecting 'STRING', 'NUMBER', 'ID', 'DATA', got 'INVALID'

我不知道有什么内置方法,但您可以创建一个模板助手来为您执行此操作。

像这样:

Ember.Handlebars.helper('array-value', function(array, key, options) {
  return array[key];
});

在你的模板中你会调用:

{{ array-value record col.field }}

这是一个jsbin example