#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}}

本节完

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值