我在使用 Handlebars 编译模板时遇到问题。我觉得我完全错过了一些重要的东西,但尽我所能,我似乎无法解决它,或者在网上找到任何关于为什么这种特殊情况会出现的信息。
我正在使用 gulp-handlebars 使用 Gulp 任务进行编译。吞咽任务是:
gulp.task('build-hbs', function(){
gulp.src('root/app/src/hbs/*.hbs')
.pipe(handlebars())
.on('error', notify.onError({
message: 'Error: <%= error.message %>'
}))
.pipe(declare({
namespace: 'Handlebars.templates',
noRedeclare: true // Avoid duplicate declarations
}))
.pipe(concat('templates.js'))
.pipe(gulp.dest('root/app/js/templates/'));
});
对于简单的模板,一切正常,但是我现在尝试使用一个简单的助手(注意:使用非编译模板时,助手工作正常)。帮手是:
Handlebars.registerHelper('gravatar', function(hash, size) {
var grav = '<img src="http://www.gravatar.com/avatar/' + hash + '.jpg?r=g&d=mm&s=' + size + '">';
return new Handlebars.SafeString(grav);
});
模板本身如下所示:
<div id="nick"><b>{{display}}</b></div>
<div id="image">{{gravatar hash}}</div>
编译后,我得到:
this["Handlebars"] = this["Handlebars"] || {};
this["Handlebars"]["templates"] = this["Handlebars"]["templates"] || {};
this["Handlebars"]["templates"]["profile"] = {"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) {
var helper, alias1=helpers.helperMissing, alias2="function", alias3=this.escapeExpression;
return "<div id=\"nick\">\r\n <b>"
+ alias3(((helper = (helper = helpers.display || (depth0 != null ? depth0.display : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"display","hash":{},"data":data}) : helper)))
+ "</b>\r\n</div>\r\n<div id=\"image\">\r\n <img src=\"http://www.gravatar.com/avatar/"
+ alias3(((helper = (helper = helpers.hash || (depth0 != null ? depth0.hash : depth0)) != null ? helper : alias1),(typeof helper === alias2 ? helper.call(depth0,{"name":"hash","hash":{},"data":data}) : helper)))
+ "?s=32\">\r\n</div>";
},"useData":true};
在我的 JS 代码中,我执行以下操作:
$('#profile').html(Handlebars.templates.profile({
display:'user 1',
hash:'abdcef....'
}));
当我运行代码时,我收到错误:
TypeError: Cannot read property 'helperMissing' of undefined
这与编译的模板代码有关:
...
var helper, alias1=helpers.helperMissing, alias2="function", alias3=this.escapeExpression;
...
我似乎找不到添加此代码的任何理由,或者helperMissing
在 Handlebars 文档中找不到对该函数的任何引用...
任何关于为什么会发生这种情况的见解都将非常受欢迎!