handlebars.js的外部帮助文件

时间:2016-09-29 04:13:43

标签: node.js gulp handlebars.js

我正在运行一些Gulp任务并使用handlebars.js进行html模板化,但是我很难从外部js文件中获取辅助函数... documentation here没有&# 39;真正解释外部文件应该如何看待,所以我希望有人可以帮助我。

这是我拥有的



/**** gulpfile.js ****/

var gulp = require('gulp');
var hb = require('gulp-hb');

gulp.task('default', function () {
    return gulp
        .src('./src/{,posts/}*.html')
        .pipe(hb({
            partials: './src/assets/partials/**/*.hbs',
            helpers: './src/assets/helpers/*.js',
            data: {
              people: [
                {firstName: "Yehuda", lastName: "Katz"},
                {firstName: "Carl", lastName: "Lerche"},
                {firstName: "Alan", lastName: "Johnson"}
              ]
            }
        }))
        .pipe(gulp.dest('./web'));
});

/**** External js file .../helpers/helpers.js ****/

Handlebars.registerHelper('list', function(items, options) {
  var out = "<ul>";

  for(var i=0, l=items.length; i<l; i++) {
    out = out + "<li>" + options.fn(items[i]) + "</li>";
  }

  return out + "</ul>";
});
&#13;
<!-- Handlebars html template -->
{{#list people}}{{firstName}} {{lastName}}{{/list}}
&#13;
&#13;
&#13;

发出错误消息:

[14:10:13] ReferenceError: Handlebars is not defined
at Object.<anonymous> (/Applications/MAMP/htdocs/helpers/src/assets/helpers/helpers.js:1:63)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at mapper (/Applications/MAMP/htdocs/helpers/node_modules/gulp-hb/node_modules/handlebars-wax/node_modules/require-glob/src/require-glob.js:51:12)
at Array.map (native)
at mapReduce (/Applications/MAMP/htdocs/helpers/node_modules/gulp-hb/node_modules/handlebars-wax/node_modules/require-glob/src/require-glob.js:87:4)

1 个答案:

答案 0 :(得分:2)

<强>更新 对不起,我应该仔细查看文档。

您应该将函数添加到传递给

的对象中的helpers属性
hb({
    helpers:{
         list: function (){}
    }
})

或者,如果您将路径传递给帮助者文件,则只需使用函数导出对象,因此您根本不需要访问HandleBars。

//helpers.js
module.exports = {
      list: function (){}
};

<强>不正确 您需要使用gulp-hb模块并使用其属性 handlebars

var HandleBars = require('gulp-hb').handlebars;

HandleBars.registerHelper(...);