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

后端 未结 1 1075
滥情空心
滥情空心 2020-12-19 19:32

I just want to run the template string against an object and examine the result

I have a string that is a template. I\'ve \"compiled\" it. Now I want to run it aga

相关标签:
1条回答
  • 2020-12-19 20:14

    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

    0 讨论(0)
提交回复
热议问题