遍历 ember.js handlebars 模板中的键值

Iterating through key-values in ember.js handlebars template

我有一个 javascript 对象

this.attributes = {
            key: value,
            // etc..
        }

我想遍历它并输出 key:value

这是我的解决方案:

import Ember from 'ember';

export default Ember.Component.extend({
init() {
    this._super(...arguments);
    this.attributes = {
        'SKU': '123',
        'UPC': 'ABC',
        'Title': 'Hour Glass'
       }

},

ProductAttributes: Ember.computed('attributes', function() {

    var attribs = this.get('attributes');
    var kvp = Object.keys(attribs).map(key => {
        return {
            'attribute_name': key,
            'attribute_value': attribs[key]
        };
    });
    return kvp;
})});

我想出的模板:

{{#each ProductAttributes as |attribute|}}
    {{attribute.attribute_name}} : {{attribute.attribute_value}}
{{/each}}

我对这个解决方案不满意,因为它看起来很麻烦:首先我将对象转换为具有非动态键 attribute_nameattribute_value 的辅助对象数组,然后我引用非直接在我的模板中的动态名称。

它工作正常,但有更好的方法吗?

我对此的建议与您在问题解释中已经描述的解决方案没有太大区别;但我的建议将为您提供更可重用且更像 each-in 帮助程序的方法:

如何使用名为 each-in-component 的位置参数创建无标记上下文组件并将所有计算的 属性 定义移动到该组件。我使用的是 Ember 2.x 语法,但我想 Ember 1.x 不会有太大的不同;这样该组件将是……。喜欢:

import Ember from 'ember';

export default Ember.Component.extend({
  objectProperties: Ember.computed('object', function() {
    let object = this.get('object');
    return Object.keys(object).map(key => {
        return {
            'key': key,
            'value': Ember.get(object, key)
        };
    });
  }),

  tagName: ''
}).reopenClass({
  positionalParams: ['object']
});

和相应的组件模板将产生计算的 属性 数组:

{{#each objectProperties as |objectProperty|}}
    {{yield objectProperty.key objectProperty.value}}
{{/each}}

因此您现在可以像常规一样使用该组件 each-in; Ember 1.x.

中不存在
{{#each-in-component attributes as |key value|}}
    {{key}} : {{value}}<br>
{{/each-in-component}}

采用这种方法;您可以多次重复使用同一个组件,您不想在自己的组件中使用的代码将位于 each-in-component 内。我已经总结了我的解决方案,以在下面 twiddle 中说明它的实际应用。希望有用。