如何在ember.js组件模板中生成多个内容? [英] How can I yield multiple pieces of content into an ember.js component template?
问题描述
目标是定义具有由调用者声明的多个内容块的HTML结构。例如,标题,正文和内容。生成的标记应该是:
The goal is to define a structure of HTML that has more than one block of content that is declared by the caller. For example, a header, body, and content. The resulting markup should be:
<header>My header</header>
<div class="body">My body</div>
<footer>My footer</footer>
实例化组件的模板将定义三个部分中的每一个,我的头
,我的身体
和我的页脚
。
The template instantiating the component would define each of the three sections, My header
, My body
, and My footer
.
使用Ruby on Rails,您将使用 content_for:header
从调用者捕获标头内容, yield:header
来插值它。
With Ruby on Rails, you would use content_for :header
to capture the header content from the caller, and yield :header
to interpolate it.
这是否可能在ember.js?
Is this possible in ember.js?
推荐答案
从ember v1.10开始,yield接受参数。但是,手柄还不允许对变量值进行内联比较。通过在组件上定义一些属性,我们可以很接近rails。
As of ember v1.10, yield accepts parameters. However handlebars doesn't yet allow for inline comparisons of variable values. By defining some properties on the component, we can get pretty close to what rails does.
根据上述示例,组件的模板如下所示:
Per the above example, the component's template would look like:
<header>{{yield header}}</header>
<div class="body">{{yield body}}</div>
<footer>{{yield footer}}</footer>
组件定义将解析yield语句的变量参数:
And the component definition would resolve the variable arguments to the yield statements:
export default Ember.Component.extend({
header: {isHeader: true},
footer: {isFooter: true},
body: {isBody: true}
});
这意味着 {{yield header}}
实际上是向消费模板生成一个对象 {isHeader:true}
。所以我们可以使用一个嵌套的if / else结构来声明这三个部分:
This means that {{yield header}}
is actually yielding an object {isHeader: true}
to the consuming template. So we can use a nested if/else structure to declare the three sections like this:
{{#my-comp as |section|}}
{{#if section.isHeader}}
My header
{{else if section.isBody}}
My body
{{else if section.isFooter}}
My footer
{{/if}}
{{/my-comp}}
这篇关于如何在ember.js组件模板中生成多个内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!