我只想对一个对象运行模板字符串并检查结果

我有一个作为模板的字符串。我已经“编译”了它。现在,我想对一个对象运行它并检查结果。

但这不起作用:

var template = '<div>{{#each items}}<div>{{item}}</div>{{/each}}</div>';
var compiled = Ember.Handlebars.compile(template);
var result = compiled({ items: [1, 2, 3] }); // ERRORS

我想要得到的是针对对象运行编译后的字符串的DOM结果。换句话说,一组看起来像这样的DOM元素:

<div>
  <div>1</div>
  <div>2</div>
  <div>3</div>
</div>

看来Ember.Handlebars.compile与Ember应用程序的其他部分紧密耦合,以至于它期望在我传递编译函数的上下文中填充很多东西。我还没有弄清楚所有这些东西是什么,或者是否有更好的方法来创建传递给已编译函数的上下文。

其他事情:
  • 我不想使用普通的“非Ember”车把。
  • 如果可以的话,我想避免创建Ember应用程序。
  • 我真的不想回答有关“为什么”我想这样做的问题。这就是我要做的。 :P
  • 最佳答案

    为什么要这样做? ;)

    坦白地说,最简单的方法是创建 View 。由于数据绑定(bind)等原因,Ember在调用compile时会挂接一堆精美的渲染内容,因此很难直接通过compile函数创建它(它传入了大量其他内容,例如缓冲区等)。

    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');
    



    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
    });
    

    或者您可以挂接到didInsertElement回调
    var foo = view.create(blah);
    
    foo.didInsertElement = function(){
      console.log(foo.$().html());
    }
    
    foo.appendTo('#blah');
    

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

    创建Ember车把模板时,绑定(bind)仍然完好无损,因此您可以修改传入的对象,它将更新模板。

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

    07-24 09:50
    查看更多