我只想对一个对象运行模板字符串并检查结果
我有一个字符串,它是一个模板。我已经“编译”了它。现在我想针对一个对象运行它并检查结果。
但这行不通:
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” Handlebars 。
- 如果可以的话,我想避免创建 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 handlebars 模板时,绑定(bind)仍然完好无损,因此您可以修改传入的对象,它会更新模板。
关于javascript - 在没有 Ember 应用程序的情况下编译 Ember 模板字符串并以编程方式运行它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24274086/