使用“Ember”方式呈现侧边栏

时间:2013-12-25 10:02:18

标签: javascript ember.js

使用Ember.js v1.2.0,我正在尝试将侧边栏模板渲染到指定的插座中。模板可能根据当前路线而不同。我正在努力想出“Ember”方法来做到这一点。

这是我到目前为止的要点:

应用程序/模板/ application.hbs

{{outlet sidebar}}

应用程序/路由/ application.js中

var ApplicationRoute = Ember.Route.extend({
  renderTemplate: function(controller, model) {
    var sidebar = controller.get('sidebar') || 'application';
    this._super();
    this.render('sidebar/' + sidebar, {
      into: 'application',
      outlet: 'sidebar'
    });
  }
});

应用程序/路由/ docs.js

var DocsRoute = Ember.Route.extend({
  renderTemplate: function(controller, model) {
    this.controllerFor('application').set('sidebar', 'docs');
    this.render();
  }
});

这不起作用,并且感觉不太Ember-ish。帮助

2 个答案:

答案 0 :(得分:6)

如果我正确地取消了问题,那么侧栏总是由主路线定义。然后你可以在每个路线的renderTemplate中设置侧边栏:

var ApplicationRoute = Ember.Route.extend({
  renderTemplate: function(controller, model) {
    this.render();
    this.render('sidebar/application', {
      into: 'application',
      outlet: 'sidebar'
    });
 }
});

var DocsRoute = Ember.Route.extend({
  renderTemplate: function(controller, model) {
    this.render();
    this.render('sidebar/docs', {
      into: 'application',
      outlet: 'sidebar'
    });
 }
});

var AnotherRoute = Ember.Route.extend({
  renderTemplate: function(controller, model) {
    this.render();
    this.render('sidebar/another', {
      into: 'application',
      outlet: 'sidebar'
    });
 }
});

如果你有很多这些路线并且你不想每次手动编写renderTemplate,那么你可以定义自动执行此操作的抽象路由类,并在需要侧边栏的每个路径中扩展该类。

var RouteWithSidebar = Ember.Route.extend({
  routeName : function() {
    var routeName = this.constructor.toString();
    // Remove 'Route'
    routeName = routeName.replace('Route', '');
    // Make first letter lowercase
    routeName = routeName.charAt(0).toLowerCase() + routeName.substr(1);
    return routeName;
  },
  renderTemplate: function(controller, model) {
    this.render();
    this.render('sidebar/' + this.routeName(), {
      into: 'application',
      outlet: 'sidebar'
    });
 }
});

答案 1 :(得分:1)

我最近写了一篇名为Model-based sidebars in Ember的博客文章。更好的方法是使用嵌套路由,其中​​父路由呈现侧边栏:

import Ember from 'ember';  
import config from './config/environment';

var Router = Ember.Router.extend({  
  location: config.locationType
});

Router.map(function() {  
  this.route('authors', {path: '/authors'}, function() {
      this.route('books', {path: '/:account_id/books'});
  });
});

export default Router;

这比使用命名出口要简洁得多,并且不需要弄乱路线的renderTemplate功能。此外,当您需要在侧边栏中显示模型数据时,接受的答案会变得非常复杂,因为每条路线都需要多个模型。

博客文章中有更多详细信息和指向GitHub上示例的链接。