Handlebars のコンパイル済みテンプレートに問題があります。何か重要なことを完全に見逃しているように感じますが、できる限り試してみても、解決できないようです。または、この特定の状況がなぜ現れているのかについてオンラインで情報を見つけることもできません.
gulp-handlebars を使用して Gulp タスクを使用してコンパイルしています。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 ドキュメント内の関数への参照を見つけることができないようです...
なぜこれが起こっているのかについての洞察は大歓迎です!