在Ember运行时动态编译HTMLBars模板

在Ember运行时动态编译HTMLBars模板

本文介绍了在Ember运行时动态编译HTMLBars模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Ember的客户端上在运行时动态编译(然后呈现)HTMLBars模板。我该怎么做?

I want to dynamically compile (and then render) a HTMLBars template at runtime, on the client in Ember. How can I do this?

推荐答案

由于Ember 2.10现在正在使用Glimmer,因此这里的操作可能有些棘手。为了编译模板,您需要在应用程序中包含 ember-template-compiler.js 。我建议使用 ember-browserify ember-source

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();
  }),
});

经测试,您的内容可以包含从Ember助手到自定义组件的任何内容,甚至包括操作绑定。

As tested, your content can contain anything from Ember helpers to your custom components, even your action bindings.

例如

<ul>
  <li>{{#link-to 'index'}}Home{{/link-to}}</li>
</ul>
<div {{action 'yourCustomAction'}}>
  {{your-custom-component params=yourCustomParams model=model flag=true}}
</div>

现在,让我们使用 {{partial} } 助手。

Now, let's do the magic in your template by using {{partial}} helper.

...

{{partial 'YOUR_TEMPLATE_NAME'}}

...

此方法在Ember 2.13中有效弃用警告,它将在以后的更新中使用。请注意, Ember.TEMPLATES 是全局变量,引擎似乎以某种方式对其进行了缓存,因此请勿将新值重新分配给现有值。

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运行时动态编译HTMLBars模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:55