2014-05-14 33 views
4

我使用的把手與節點,並且工作正常:如何註冊和使用Handlebars助手和Node?

require('handlebars'); 
var template = require('./templates/test-template.handlebars'); 
var markup = template({ 'some': 'data' }); 
console.log(markup); 

這工作正常。但是,我需要在我的模板中註冊並使用自定義助手。所以,現在我的代碼看起來是這樣的:

var Handlebars = require('handlebars'); 

Handlebars.registerHelper('ifEqual', function(attribute, value) { 
    if (attribute == value) { 
     return options.fn(this); 
    } 
    else { 
     return options.inverse(this); 
    } 
}); 

var template = require('./templates/test-template.handlebars'); 
var markup = template({ 'some': 'data' }); 
console.log(markup); 

但現在當我運行我的腳本,我得到

Error: Missing helper: 'ifEqual'

所以:我怎麼能定義和節點使用自定義的助手?

回答

5

我想通了。我需要這樣做:

var Handlebars = require('handlebars/runtime')['default']; 

一個非常酷的是,這甚至可以在瀏覽器中使用Browserify。

然而,我發現一個更好的方法(也可能是「正確」的方式)是通過(shell命令)預編譯把手模板:

handlebars ./templates/ -c handlebars -f templates.js 

那麼我這樣做:

var Handlebars = require('handlebars'); 
require('./templates'); 
require('./helpers/logic'); 

module.exports.something = function() { 
    ... 
    template = Handlebars.templates['template_name_here']; 
    ... 
}; 
+0

請問您能詳細介紹一下嗎? 'module.exports.something = function(){ ... template = Handlebars.templates ['template_name_here']; ... };' 你的意思是出口。什麼? – peterkr

+0

module.exports.something只是需要使用我定義的Handlebars模板的CommonJS模塊的一個功能。 –

1

這是我做到的。
我想現在它有點不同。

const Handlebars = require('handlebars'); 

module.exports = function(){ 
    Handlebars.registerHelper('stringify', function(stuff) { 
     return JSON.stringify(stuff); 
    }); 
}; 

然後我做了一個腳本來調用所有幫助器上的require,讓它們跑起來。

// Helpers Builder 
let helpersPath = Path.join(__dirname, 'helpers'); 
fs.readdir(helpersPath, (err, files) => { 
    if (err) {throw err;} 
    files.filter((f) => { 
     return !!~f.indexOf('.js'); 
    }).forEach((jsf) => { 
     require(Path.join(helpersPath, jsf))(); 
    }); 
}); 

或簡單的方法

require('./helpers/stringify')(); 

事實上,你甚至不必須將其導出爲一個功能,您可以只是沒有在所有出口任何東西,只是從另一個調用JS需要同列功能文件最後的參數。