2

想象一下,我有一个 Ember 组件,出于这个问题的目的,它只是将其内容包装在 a 中div,并添加一些文本:

<div class="Component">
  Value is: {{yield}}
<div>

所以我称之为

{{#component}}
  {{model.text}}
{{/component}}

一切都很好。但是,如果model.text为空/空/未定义,我根本不想生成该<div class="Component">部分。我怎样才能做到这一点?我当然可以

{{#if model.text}}
  {{#component}}
    {{model.text}}
  {{/component}}
{{/if}}

但这似乎是重复的。

我真正想做的是能够将组件定义为

{{if yield}} {{! made-up syntax; of course it doesn't work }}
  <div class="Component">
    Value is: {{yield}}
  <div>
{{/if}}

或者,或者在 component.js

yieldNotEmpty: Ember.computed.bool('yield') // made-up syntax; doesn't work

然后在组件的 template.hbs 中

{{if yieldNotEmpty}}
  <div class="Component">
    Value is: {{yield}}
  <div>
{{/if}}

关于如何处理这种情况的任何想法?

4

2 回答 2

5

Ember 1.13.0 开始,引入了一个新的模板词hasBlockhasBlock当以块形式调用组件时将为真。例如:

{{#if hasBlock}}
    {{! yield }}
{{else}}
    {{! regular component }}
{{/if}}

因此,对于您的示例,这将给出:

{{#if hasBlock}}
    <div class="Component">
        Value is: {{yield}}
    <div>
{{/if}}

引入的另一个关键字是hasBlockParams,如果使用块参数调用组件(使用 以块形式调用),它将是真实的as |someParam|

于 2015-08-12T19:56:08.783 回答
0

您可以通过以下方式缩短 if 语句:

// component template
{{#if showContent}}
    <div class="Component">
        Value is: {{yield}}
    </div>
{{/if}}

// some other template
{{#component showContent=model.text}}
    {{model.text}}
{{/component}}

缺点是组件总是会创建一个 div 元素,即使它没有内容。所以对我来说,你的组件周围的 if 语句似乎是更好的解决方案,即使它添加了一些样板代码。

于 2015-04-20T16:27:42.667 回答