How can I register and use the Handlebars helper with Node?

I use Handlebars with Node and this works great:

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

It works great. However, I need to register and use my own 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 my own helper in Node?

+4
source share
2 answers

I get it. I needed to do this:

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

Which is really cool, it even works in a browser with Browserify.

, (, , "" ) , Handlebars ( ):

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'];
    ...
};
+5

.
, .

const Handlebars = require('handlebars');

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

script, , .

// 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 .

+1

Source: https://habr.com/ru/post/1540604/


All Articles