Question

I'm using Handlebars with Node, and that works fine:

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

That works fine. However, I need to register and use a custom helper in my template. So, now my code looks like this:

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);

But now when I run my script, I get

Error: Missing helper: 'ifEqual'

So: how can I define and use a custom helper in Node?

Was it helpful?

Solution

I figured it out. I needed to do this:

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

One what's really cool is, this even works in the browser with Browserify.

However, I found that an even better way (and probably the "correct" way) is to precompile Handlebars templates via (shell command):

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

Then I do this:

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

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

OTHER TIPS

Here is the way i did it.
I guess nowadays its a bit different.

const Handlebars = require('handlebars');

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

then i made a little script to call require on all the helpers just so they get ran.

// 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))();
    });
});

OR the simple way

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

in fact you dont even have to export it as a function you can just not export anything at all and just call require from another js file with out the function params at the end.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top