一种可能的方法是使用view 专用于呈现用户定义的模板。然后通过设置它的template 变量并重新渲染它,模板可以动态改变。
例子,
http://emberjs.jsbin.com/yexizoyi/1/edit
hbs
<script type="text/x-handlebars">
<h2> Welcome to Ember.js</h2>
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="test">
this is the test,
{{view view.userTemplate}}
<button {{action "changeTemplate" 1 target="view"}}>change to Template 1</button>
<button {{action "changeTemplate" 2 target="view"}}>change to Template 2</button>
</script>
js
App.Router.map(function() {
this.route("test");
});
App.IndexRoute = Ember.Route.extend({
beforeModel: function() {
this.transitionTo("test");
}
});
App.UserTemplateView = Ember.View.extend({
template:Ember.Handlebars.compile("initial default template <b>{{view.parentView.parentVar}}</b>")
});
App.TestView = Ember.View.extend({
parentVar:"this is a parent variable",
userTemplate:App.UserTemplateView.create(),
actions:{
changeTemplate:function(templateId){
if(templateId===1){
this.get("userTemplate").set("template",Ember.Handlebars.compile("this is template 1 <b>{{view.parentView.parentVar}}</b>"));
this.get("userTemplate").rerender();
}else{
this.get("userTemplate").set("template",Ember.Handlebars.compile("this is template 2 <b>{{view.parentView.parentVar}}</b>"));
this.get("userTemplate").rerender();
}
}
}
});
这也可以通过使用ContainerView、http://emberjs.com/guides/views/manually-managing-view-hierarchy/来实现
例如,
http://emberjs.jsbin.com/luzufixi/1/edit
edit - 对 cmets 的补充和 Sam Selikoff 使用助手的良好解决方案
这是使用前一个概念的一个更粗略的示例,以及路由器模型和由通用View 对象支持的{{view}} 助手,即PreviewTemplateView。
http://emberjs.jsbin.com/tonapaqi/1/edit
http://emberjs.jsbin.com/tonapaqi/1#/test/1
http://emberjs.jsbin.com/tonapaqi/1#/test/2
hbs - 使用所需上下文调用 {{view}} 助手,如果它包含 template 属性,则初始默认模板将更改。
{{view App.PreviewTemplateView contextBinding="this"}}
js
App.Router.map(function() {
this.route("test",{path:"test/:tmpl_id"});
});
App.IndexRoute = Ember.Route.extend({
beforeModel: function() {
this.transitionTo("test",1);
}
});
App.TestRoute = Ember.Route.extend({
model:function(params){
if(params.tmpl_id==1){
return {template:"this is template 1 <b>{{view.parentView.parentVar}},param from context of model:{{someParams.param1}}</b>",someParams:{param1:"p1",param2:"p2"}};
}else{
return {template:"this is template 2 <b>{{view.parentView.parentVar}},param from context of model:{{someParams.param2}}</b>",someParams:{param1:"p1",param2:"p2"}};
}
}
});
App.PreviewTemplateView = Ember.View.extend({
template:Ember.Handlebars.compile("initial default template"),
init:function(){
this._super();
this.refreshTemplate();
},
refreshTemplate:function(){
this.set("template",Ember.Handlebars.compile(this.get("context").get("template")));
this.rerender();
}.observes("context.template")
});
App.TestView = Ember.View.extend({
parentVar:"this is a parent variable"
});