How to compile new templates at runtime in meteor?

2019-05-14 00:58发布

How to compile new templates at runtime in meteor using 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);

1条回答
一纸荒年 Trace。
2楼-- · 2019-05-14 01:18

Currently there is no way to compile the Handlebars string directly. Meteor wraps Handlebars and only provides a compile method for an ast (abstract syntax tree) not a string directly. However, you can provide your own function that isn't a Handlebars function. It's not a public API but you can create a Meteor template this way (for now unless the API changes):

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

So, this will create a template in the Template namespace and give you all the good Meteor functionality for the template (e.g. reactivity, events, landmarks, etc.).

You can also learn more about what's going on behind the scenes by watching this series of screencasts on Spark - the underlying rendering engine for Meteor.

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

查看更多
登录 后发表回答