在Ember 2.5中运行时动态地编译一个HTMLBars模板 [英] Dynamically compile a HTMLBars template at runtime in Ember 2.5
问题描述
由于Ember 2.10正在使用Glimmer,所以这里可能有点棘手。为了编译模板,您需要在应用程序中包含 ember-template-compiler.js
。我建议使用 ember-browserify
和 ember-source
。
在控制器中,导入编译器,如下所示。
从ember导入Ember;
import'npm:ember-source / dist / ember-template-compiler'的编译器;
导出默认值Ember.Controller.extend({
compileContent(){
const template = Compiler.compile(this.get('dynamicContent'));
Ember.TEMPLATES [`YOUR_TEMPLATE_NAME`] = template;
},
//我们在这里观察到内容更改
contentDidUpdate:Ember.observer('dynamicContent',function(){
this.compileContent();
}),
});
如测试,您的内容可以包含任何从Ember帮助者到您的自定义组件,甚至是您的操作绑定。
例如
< ul>
< li> {{#link-to'index'}}首页{{/ link-to}}< / li>
< / ul>
< div {{action'yourCustomAction'}}>
{{your-custom-component params = yourCustomParams model = model flag = true}}
< / div>
现在,让我们使用 {{partial}
帮助者。
...
{{partial'YOUR_TEMPLATE_NAME '}}
...
此方法适用于Ember 2.13,没有弃用警告,它应该在将来的更新中工作。请注意, Ember.TEMPLATES
是全局变量,引擎似乎以某种方式缓存,所以不要将新值重新分配给现有的值。
I want to dynamically compile (and then render) a HTMLBars template at runtime, on the client in Ember 2.5. How can I do this?
Since Ember 2.10 is now using Glimmer, things might be a bit tricky here. In order to compile a template, you need to include ember-template-compiler.js
to your application. I'd recommend using ember-browserify
and ember-source
.
In your controller, import the compiler as the following.
import Ember from 'ember';
import Compiler from 'npm:ember-source/dist/ember-template-compiler';
export default Ember.Controller.extend({
compileContent() {
const template = Compiler.compile(this.get('dynamicContent'));
Ember.TEMPLATES[`YOUR_TEMPLATE_NAME`] = template;
},
// we observe content changes here
contentDidUpdate: Ember.observer('dynamicContent', function() {
this.compileContent();
}),
});
As tested, your content can contain anything from Ember helpers to your custom components, even your action bindings.
e.g.
<ul>
<li>{{#link-to 'index'}}Home{{/link-to}}</li>
</ul>
<div {{action 'yourCustomAction'}}>
{{your-custom-component params=yourCustomParams model=model flag=true}}
</div>
Now, let's do the magic in your template by using {{partial}}
helper.
...
{{partial 'YOUR_TEMPLATE_NAME'}}
...
This method works in Ember 2.13 without deprecation warnings, it should work in future updates. Please note that Ember.TEMPLATES
is global variable and the engine seems to cache it somehow, so do not reassign new values to the existing one.
这篇关于在Ember 2.5中运行时动态地编译一个HTMLBars模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!