Ember:基于' yield'的内容控制组件行为。

时间:2015-04-20 16:09:40

标签: ember.js htmlbars

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

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

所以我称之为

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

一切都很好。但是,如果model.text为空/ null /未定义,我根本不想生成<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}}

有关如何处理此案的任何想法?

2 个答案:

答案 0 :(得分:5)

Ember 1.13.0起,引入了新的模板字hasBlock。以块形式调用组件时,hasBlock将为true。例如:

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

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

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

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

答案 1 :(得分: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语句似乎也是更好的解决方案。