如何将多条内容生成到 ember.js 组件模板中? [英] How can I yield multiple pieces of content into an ember.js component template?

查看:14
本文介绍了如何将多条内容生成到 ember.js 组件模板中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标是定义一种 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>

实例化组件的模板将定义三个部分中的每一个,My headerMy bodyMy 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 接受参数.然而,handlebars 还不允许对变量值进行内联比较.通过在组件上定义一些属性,我们可以非常接近 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆