簡體   English   中英

遍歷ember.js車把模板中的鍵值

[英]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 我已經結束了我的解決方案來說明它在以下的動作玩弄 我希望它能起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM