2016-09-29 60 views
0

我正在運行一些Gulp任務,並使用html模板的handlebars.js,但我努力得到幫助函數從外部js文件工作... documentation here不真正解釋外部文件應該如何顯示,所以我希望有人能幫助我。handlebars.js的外部幫手文件

這裏就是我有

/**** 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>"; 
 
});
<!-- Handlebars html template --> 
 
{{#list people}}{{firstName}} {{lastName}}{{/list}}

芽出來的錯誤信息:

[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

更新 對不起,我應該在文檔更仔細地看着。

您應該添加功能傭工財產對象傳遞給

hb({ 
    helpers:{ 
     list: function(){} 
    } 
}) 

或者,如果你傳遞一個路徑助手文件,與功能你只是出口對象,所以你並不需要獲得在車把所有。

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

錯誤 需要導入吞氣-HB模塊,並使用它的屬性車把

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

HandleBars.registerHelper(...); 
+0

部屋Molda,感謝堆的幫助......現在它拍攝出「錯誤:缺少幫手:‘清單’ – WillW

+0

@WillW抱歉,我已經更新了我的答案 – Molda

+0

嘿@Molda,一個大感謝如果我問你是否找到了文檔? – WillW