我目前正在使用它们的同一个 HTML 文件中定义我的 Handlebars 模板。
是否可以将它们定义为外部模板,可以在页面加载时调用?
最佳答案
对于那些像我一样通过 Google 搜索到达这里的人,我终于在这篇文章中找到了完美的答案,请查看:
http://berzniz.com/post/24743062344/handling-handlebarsjs-like-a-pro
基本上你需要实现一个方法, getTemplate :
Handlebars.getTemplate = function(name) {
if (Handlebars.templates === undefined || Handlebars.templates[name] === undefined) {
$.ajax({
url : 'templatesfolder/' + name + '.handlebars',
success : function(data) {
if (Handlebars.templates === undefined) {
Handlebars.templates = {};
}
Handlebars.templates[name] = Handlebars.compile(data);
},
async : false
});
}
return Handlebars.templates[name];
};
然后用它调用你的模板:
var compiledTemplate = Handlebars.getTemplate('hello');
var html = compiledTemplate({ name : 'World' });
这样,如果您预编译模板(非常适合生产使用),它将直接找到它,否则它将获取模板并在浏览器中编译它(这就是您在开发中的工作方式)。
关于templates - 如何在外部文件中定义 Handlebar.js 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23013447/