#5 遍歷Hash對象

英文原版:https://guides.emberjs.com/v2.13.0/templates/displaying-the-keys-in-an-object/

如果你需要在模板中顯示javascript對象的key或者value,那麼你可以使用{{#each-in}}助手:

/app/components/store-categories.js

import Ember from 'ember';

export default Ember.Component.extend({
  willRender() {
    // Set the "categories" property to a JavaScript object
    // with the category name as the key and the value a list
    // of products.
    this.set('categories', {
      'Bourbons': ['Bulleit', 'Four Roses', 'Woodford Reserve'],
      'Ryes': ['WhistlePig', 'High West']
    });
  }
});
/app/templates/components/store-categories.hbs

<ul>
  {{#each-in categories as |category products|}}
    <li>{{category}}
      <ol>
        {{#each products as |product|}}
          <li>{{product}}</li>
        {{/each}}
      </ol>
    </li>
  {{/each-in}}
</ul>

{{#each-in}}會按照key來進行遍歷。其中 category參數就是對象中的key,products參數是key對應的value。

上面的例子最終會得到下面的結果:

<ul>
  <li>Bourbons
    <ol>
      <li>Bulleit</li>
      <li>Four Roses</li>
      <li>Woodford Reserve</li>
    </ol>
  </li>
  <li>Ryes
    <ol>
      <li>WhistlePig</li>
      <li>High West</li>
    </ol>
  </li>
</ul>

排序

上面例子中數據展示的順序與定義時的順序是一樣的。但是,如果你想要人爲的對它進行排序,那麼你需要利用key來構建一個數組,並且通過javascript的方法,如:sort()來對此數組進行排序,然後使用{{#each}}助手來輸出。

空集合

{{#each-in}}助手同樣也帶有{{else}},如果被遍歷的對象爲空,null或者undefined。那麼就會去渲染{{else}}塊中的內容:

{{#each-in people as |name person|}}
  Hello, {{name}}! You are {{person.age}} years old.
{{else}}
  Sorry, nobody is here.
{{/each-in}}

本節完

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章