templatesember.jscompilationhtmlbars

Dynamically compile a HTMLBars template at runtime in Ember


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


Solution

  • 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.