在 Ember 中在运行时动态编译 HTMLBars 模板 [英] Dynamically compile a HTMLBars template at runtime in Ember

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

问题描述

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

解决方案

由于 Ember 2.10 现在使用 Glimmer,这里的事情可能有点棘手.为了编译模板,您需要将 ember-template-compiler.js 包含到您的应用程序中.我建议使用 ember-browserifyember-source.

在您的控制器中,按如下方式导入编译器.

从'ember'导入Ember;从npm:ember-source/dist/ember-template-compiler"导入编译器;导出默认 Ember.Controller.extend({编译内容(){const 模板 = Compiler.compile(this.get('dynamicContent'));Ember.TEMPLATES[`YOUR_TEMPLATE_NAME`] = 模板;},//我们在这里观察内容的变化contentDidUpdate: Ember.observer('dynamicContent', function() {this.compileContent();}),});

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

例如

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆