我最近正在创建一个具有复杂布局的应用程序,因此我试图找到一种优雅的方式来使用大量模板并使它们按照我的意愿工作。
首先,我有一些 UI 组件需要安装,这些组件与模型没有关系,不需要使用路由来管理状态,所以我使用 {{render}}
helper 来做类似的事情:
<script type="text/x-handlebars">
<div class="wrapper">
{{render component_1}}
{{render component_2}}
<div class="main">
{{outlet}}
</div>
</div>
</script>
这种方法是有效的,但老实说,在执行此操作之前我对 renderTemplate
方法一无所知。几天后,我尝试这样做:
<script type="text/x-handlebars">
<div class="wrapper">
{{outlet component_1}}
{{outlet component_2}}
<div class="main">
{{outlet main}}
</div>
</div>
</script>
并在路由中添加额外的代码:
MyApp.ApplicationRoute = Ember.Route.extend({
renderTemplate: function() {
this.render();
this.render('component_1', {
outlet: 'component_1',
into: 'application'
});
this.render('component_2', {
outlet: 'component_2',
into: 'application'
});
}
});
然后我得到了相同的结果。
现在,我正在努力在这两种方法之间做出选择。我更喜欢第一个,因为我认为这些 UI 组件永远不会使用路由,因为它们没有任何状态,因此没有必要在 ApplicationRoute
中编写额外的代码。但仍然有两个问题:
- 每个相关教程都使用后一种,我没有足够的信心使用
{{render}}
。 - 更重要的是:我无法预测我的应用程序的进一步更改,我不知道哪个应用程序会更灵活地适应更改,或者为我提供更多的可扩展性。
所以我需要一些解释和建议才能明智地使用 {{render}}
和 renderTemplate
,感谢您的帮助。
最佳答案
如果它们是组件,而不是成熟的路由,只需在模板中使用渲染即可。
{{render}} 在当前上下文中使用相同的命名 Controller 和模板。所以这意味着它从当前路由中获取上下文。如果存在同名的 View 类,则使用该 View 类。如果指定了模型,它将成为该 Controller 的模型。默认目标将是同一个 Controller 。
关于Ember.js:在模板中使用 {{render}} 帮助器和在路由中使用 renderTemplate Hook 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17003857/