Compile Ember template string and running it programmatically, without an Ember application?

久未见 提交于 2019-11-29 12:09:19

Why do you want to do this? ;)

Honestly the easiest way to do this will be to create a view. Ember hooks up a bunch of fancy rendering stuff when it calls compile due to the data binding etc, so it's difficult to create it straight from the compile function (it passes in a slew of additional stuff, like buffers etc...)

var view = Ember.View.extend({
  template:Ember.Handlebars.compile('hello <div>{{#each item in view.items}}<div>{{item}}</div>{{/each}}</div>')
});

var foo = view.create({ items: [1, 2, 3] });

foo.appendTo('#blah');

Example

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

// you must wait for all bindings to sync before you can check the contents of #blah:
var empty = $('#blah').html(); // this will be empty

Ember.run.next(function(){
  var notEmpty = $('#blah').html(); // this will have the proper result in it
});

or you can hook up to the didInsertElement callback

var foo = view.create(blah);

foo.didInsertElement = function(){
  console.log(foo.$().html());
}

foo.appendTo('#blah');

http://emberjs.jsbin.com/qeyenuyi/6/edit

The bindings are still in tact when you create a Ember handlebars template, so you can modify the object passed in and it will update the template.

http://emberjs.jsbin.com/qeyenuyi/2/edit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!