Compile template client side in ember using HTMLba

2019-01-15 15:50发布

I have created a CMS where it is be possible to use HTMLbars to create templates. The templates should be compiled client side and there is component that should display the template. I'm setting the template property of the component to a function that returns the compiled template using HTMLBars.

import Ember from 'ember';

export default Ember.Component.extend({
  content: null,
  template: function () {
    return Ember.HTMLBars.compile(this.get('content.template'));
  }
}

I've included the ember-template-compiler in my Brocfile.

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

also tested

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

But the template is never rendered.

1条回答
我只想做你的唯一
2楼-- · 2019-01-15 16:23

It should be a property, and on a component it should be layout, but it will only be evaluated once, so updating the content won't rebuild the template.

http://emberjs.jsbin.com/vayereqapo/1/edit?html,js,output

Ember.Component.extend({
  content: {template: 'Hello'},
  layout: function () {
    return Ember.HTMLBars.compile(this.get('content.template'));
  }.property()
});

Rerender when template content changes:

App.FooBarComponent = Ember.Component.extend({
  content: {template: 'Hello'},
  foo: function(){
    var self = this;
    Em.run.later(function(){
      self.set('content.template', 'Bye');
      self.rerender();
    }, 3000);
  }.on('init'),
  layout: function () {
    return Ember.HTMLBars.compile(this.get('content.template'));
  }.property('content.template')
});

http://emberjs.jsbin.com/qebuxuxasu/1/edit

查看更多
登录 后发表回答