5

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.

Lillvik
  • 385
  • 4
  • 20

1 Answers1

4

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

Kingpin2k
  • 47,277
  • 10
  • 78
  • 96
  • Thanks for your answer. Will rerender trigger the layout to be compiled again? – Lillvik May 19 '15 at 06:30
  • Apparently it will, learn something new every day :) http://emberjs.jsbin.com/qebuxuxasu/1/edit – Kingpin2k May 19 '15 at 17:32
  • I tested it and the property was already there it was just missing here in my example. But I had an old template hbs file connected to the component that had precedence. After I removed the file it worked fine with template as well. – Lillvik May 20 '15 at 05:04
  • Is there any way of validating the compiled template? Now whenever the template is faulty it breaks. I would like to validate it before I insert it in the dom. – Lillvik May 22 '15 at 11:39
  • `ember-template-compiler.js` is in JSBin, but it's worth pointing out that you have to load it, in addition to Ember itself. – Max Wallace May 20 '16 at 11:09
  • this is how you can import `ember-template-compiler` w ember +2.11 https://github.com/ember-cli/ember-cli/issues/6712 – pol Sep 26 '17 at 19:39