支持块和非块组件用法



你可以通过使用 hasBlock 属性,从单个组件支持块和非块组件用法。

语法

{{#if hasBlock}}
   //code here
{{/if}}

示例

下面给出的示例指定在一个模板中支持块和非块组件用法。创建一个名为 comp-yield 的路由,并打开 router.js 文件以定义 URL 映射 −

import Ember from 'ember';                   
//Access to Ember.js library as variable Ember
import config from './config/environment'; 
//It provides access to app's configuration data as variable config 

//The const declares read only variable
const Router = Ember.Router.extend ({
   location: config.locationType,
   rootURL: config.rootURL
});

//Defines URL mappings that takes parameter as an object to create the routes
Router.map(function() {
   this.route('comp-yield');
});

export default Router;

创建 application.hbs 文件并添加以下代码 −

//link-to is a handlebar helper used for creating links
{{#link-to 'comp-yield'}}Click Here{{/link-to}}
{{outlet}} //It is a general helper, where content from other pages 
   will appear inside this section

打开在 app/routes/ 创建的 comp-yield.js 文件,并输入以下代码 −

import Ember from 'ember';

export default Ember.Route.extend ({
   model: function () {
      return {
         title: "Emberjs",
         author: "Tutorialspoint",
         body: "This is introduction"
      };
   }
});

app/templates/ 创建一个名为 comp-yield 的组件并用以下代码打开组件模板文件 comp-yield.hbs

{{#comp-yield title = title}}
   <p class = "author">by (blocked name){{author}}</p>
   {{body}}
{{/comp-yield}}
{{comp-yield title = title}}
{{outlet}}

打开在 app/templates/components/ 创建的 comp-yield.hbs 文件并输入以下代码 −

{{#if hasBlock}}
   <div class = "body">{{yield}}</div>
   {{else}}
   <div class = "body">Tutorialspoint data is missing</div>
{{/if}}
{{yield}}

输出

运行 ember 服务器;你将收到以下输出 −

Ember.js Component block and non-block component usage

当你点击链接,它将阻止名称,如下面的截图所示 −

Ember.js Component block and non-block component usage
emberjs_component.htm
广告