Dynamically compile a HTMLBars template at runtime in Ember

前端 未结 4 1659
故里飘歌
故里飘歌 2020-12-12 01:49

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

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-12 02:33

    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.

    • {{#link-to 'index'}}Home{{/link-to}}
    {{your-custom-component params=yourCustomParams model=model flag=true}}

    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.

提交回复
热议问题