Ember.js - 一个视图多个布局(登录/未登录)

时间:2013-11-14 16:44:25

标签: javascript ember.js

在我目前的Ember项目中,我有一个认证系统。某些页面只能由经过身份验证的用户查看。检查用户是否经过身份验证并控制对页面的访问权限非常简单,因此没有任何问题。

问题是我有一些经过身份验证和未经身份验证的用户都可以查看的页面。经过身份验证的用户会看到与未经过身份验证的用户不同的导航(顶部和侧边栏)(更多导航选项,设置等)。我想根据用户是否经过身份验证来更改使用的布局。问题是我似乎只能将一个布局设置为视图。

一般代码如下:

布局:

<script type="text/x-handlebars" data-template-name="authenticated_layout">
  //authenticated layout mark up
  {{yield}}
</script>

<script type="text/x-handlebars" data-template-name="not_authenticated_layout">
  //not_authenticated layout mark up
  {{yield}}
</script>

文章模板(文章可以由经过身份验证或未经过身份验证的用户查看):

<script type="text/x-handlebars" data-template-name="article">
  //article mark up
</script>

文章视图:

App.ArticleView = Ember.View.extend({
  templateName: "article",
  layoutName: //want this to be based on authentication state
  //other view code
})

我为每个布局设置了不同的视图,并根据用户是否经过身份验证,使用视图呈现模板。我看到的问题是ArticlesView不仅仅是设置布局,而且我真的不希望有两个单独的视图,只有它们的layoutName属性不同。

非常感谢任何建议。

1 个答案:

答案 0 :(得分:2)

我认为layoutName中的计算属性可以工作。

伪代码:

App.ArticleView = Ember.View.extend({
  templateName: "article",
  layoutName: function() {
    // you can use your own logic to know if the user is authenticated
    // but don't forget to add in the property(dependenKey), if needed
    return App.get('currentUser') ? 'authenticated_layout' : 'not_authenticated_layout';
  }.property('App.currentUser')
})