Dynamically compile a HTMLBars template at runtime in Ember

前端 未结 4 1653
故里飘歌
故里飘歌 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:45

    Since Ember 2.13+ (without bower by default) you need to add in your ember-cli-build.js:

    app.import('vendor/ember/ember-template-compiler.js');
    

    For Ember version prior to 2.10 you need to include it via bower (also on ember-cli-build.js)

    app.import('bower_components/ember/ember-template-compiler.js');
    

    And on the code you need to:

    Ember.TEMPLATES['mycompiledcode'] = Ember.HTMLBars.compile('{{foo-bar}} ' + 'hello' + '');
    

    In the hbs file call:

    {{partial 'mycompiledcode'}}
    

    Or you can make a component like this:

    import Ember from 'ember';
    
    export default Ember.Component.extend({
    
      layout: Ember.computed(function() {
        return Ember.HTMLBars.compile(
          '{{foo-bar}} ' + 'hello' + ''
        );
      }),
    
    });
    

    Based on solution of another answer https://stackoverflow.com/a/37345099/6505594

提交回复
热议问题