从 ember v1.10 开始,yield 接受参数。然而,handlebars 还不允许对变量值进行内联比较。通过在组件上定义一些属性,我们可以非常接近 rails 的功能。
根据上面的示例,组件的模板如下所示:
<header>{{yield header}}</header>
<div class="body">{{yield body}}</div>
<footer>{{yield footer}}</footer>
组件定义会将变量参数解析为 yield 语句:
export default Ember.Component.extend({
header: {isHeader: true},
footer: {isFooter: true},
body: {isBody: true}
});
这意味着这{{yield header}}
实际上是{isHeader: true}
向消费模板产生一个对象。所以我们可以使用嵌套的 if/else 结构来声明三个部分,如下所示:
{{#my-comp as |section|}}
{{#if section.isHeader}}
My header
{{else if section.isBody}}
My body
{{else if section.isFooter}}
My footer
{{/if}}
{{/my-comp}}