我有两个模型Admin
和User
。
我的应用程序模板如下:
//application.hbs
{{outlet}}
{{header-nav}}
如果可能的话,我想让{{header-nav}}
可定制化,我解释一下:
如果管理员
已经认证,我想呈现组件{{admin-header}}
,
如果用户
已经认证,它应该呈现{{user-header}}
。
如何在application.hbs
中动态构建要呈现的内容?
我有两个模型Admin
和User
。
我的应用程序模板如下:
//application.hbs
{{outlet}}
{{header-nav}}
如果可能的话,我想让{{header-nav}}
可定制化,我解释一下:
如果管理员
已经认证,我想呈现组件{{admin-header}}
,
如果用户
已经认证,它应该呈现{{user-header}}
。
如何在application.hbs
中动态构建要呈现的内容?
isAdmin
计算属性,代码如下:// application controller
isAdmin: Ember.computed(function() {
// your logic here
})
// application template
{{#if isAdmin}}
{{admin-header}}
{{else}}
{{user-admin}}
{{/if}}
或者您可以将其作为具有 isAdmin
属性的 header-nav
组件进行包装,如下所示:
// application template
{{header-nav isAdmin=isAdmin}}
更新 (使用 ember-simple-auth 为 @Grimmy 提供详细信息)
1) 将 currentUser
注入到 session
中(例如,https://dev59.com/-Izda4cB1Zd3GeqPhAjE#30894082)。
2) 在 beforeModel
钩子中解析 currentUser
并设置 currentUser
控制器属性:
//route
beforeModel: function() {
var self = this;
this.session.get('currentUser').then(function(user) {
self.controllerFor( self.routeName ).set('currentUser', user);
},function() {
self.controllerFor( self.routeName ).set('currentUser', null);
});
}
//controller
isAdmin: Ember.computed('currentUser.role', function() {
return (this.get('currentUser.role') === 'admin');
}),
//template
{{#if isAdmin}}
{{admin-header}}
{{else}}
{{user-admin}}
{{/if}}
//controller
roleBasedComponentName: Ember.computed('currentUser.role', function() {
return ((this.get('currentUser.role') === 'admin') ? 'admin-header' : 'user-header');
})
//template
{{component roleBasedComponentName user=currentUser}}
你可以使用{{component}}
助手,但首先需要确定组件名称,在你的控制器中:
nameForComponent: Ember.computed('user.isAdmin', function() {
// if admin return admin-header else user-header
})
然后,在您的模板中:
{{component nameForComponent}}
它是为这些使用情况而设计和引入的,不久前推出。
您还可以更花哨一些:
{{component (if user.isAdmin 'admin-header' 'user-header') }}
nameForComponent
应该返回组件名称 - 字符串 admin-header
或 user-header
。 - Daniel Kmak
this.session
是空的。你可能没有正确地包含ApplicationRouteMixin
或AuthenticatedRouteMixin
,或者其他什么问题。请参考 https://github.com/simplabs/ember-simple-auth#the-session 了解如何在路由中使用 session。还有为什么不使用 '0.8.0' 版本呢? - artych