3

如何使用 Handlebars.js 在运行时在流星中编译新模板?

var source   = '<input type="text" value"{{title}}" />' ;    
var template = ***???***.compile(my_new_template, source);
var context = {title: "My New Post", body: "This is my first post!"}
Template.my_new_template.events({
  'click': function (e,sender) {
    var that=this;
  }
});
var html = Template.my_new_template(context);
$('#workspace').append(html);
4

1 回答 1

4

目前没有办法直接编译 Handlebars 字符串。Meteor 包装了 Handlebars,只为 ast(抽象语法树)提供了编译方法,而不是直接提供字符串。但是,您可以提供自己的不是 Handlebars 函数的函数。它不是公共 API,但您可以通过这种方式创建 Meteor 模板(暂时,除非 API 更改):

< 0.6.5:

var tmpl = Meteor._def_template("templateName", function () { 
    return "some html string"; 
});

0.6.5

var tmpl = Meteor.__define__("templateName", function () { 
    return "some html string"; 
});

因此,这将在命名空间中创建一个模板,Template并为您提供模板的所有良好 Meteor 功能(例如反应性、事件、地标等)。

您还可以通过观看 Spark(Meteor 的底层渲染引擎)上的这一系列截屏视频来了解更多关于幕后发生的事情。

http://www.eventedmind.com/posts/meteor-rendering-template-functions http://www.eventedmind.com/posts/meteor-introduction-to-rendering

于 2013-02-27T23:53:23.963 回答