您的位置:首页 > Web前端 > JavaScript

#5 遍历Hash对象

2017-07-01 13:18 274 查看
英文原版: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}}


本节完
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息