Registering handlebars helpers with node does abso

2020-07-17 07:13发布

问题:

I'm attempting to write my own handlebars helpers and am getting no where. I'm using the npm hbs package (Handlebars.registerHelper didn't work) and registering it in app.js like so:

app.set('view engine', 'hbs');
var hbs = require('hbs');

hbs.registerHelper("log", function(something) {
    return console.log(something);
});

hbs.registerHelper('test', function() { 
  return console.log('test')
});

Yet {{log 'test'}} or {{test}} any where inside my template does absolutely nothing. There's no js errors being produced in the browser or terminal consoles. I know handle bars is working correctly since I have other hb variables displaying correctly. I'm at my wits end here trying to do something very simple otherwise I wouldn't embarrasses my self by asking such a simple question.

Thank you for your time.

回答1:

Thank you for your input mscdex but your response didn't work. I'll clarify how I got it working here for others new to handlebars. I was using the npm hbs package because I found good helper examples. After looking into it deeper, my previous handlebars package "express-handlebars" had some examples on the npm page that actually worked. I think my main confusion was a result of not knowing where the first variable in the declaration was being defined.

Below is the code in my app.js file that declares which handlebars package to use.

var exphbs  = require('express-handlebars');
app.engine('.hbs', exphbs({defaultLayout: 'main', extname: '.hbs'}));
app.set('view engine', 'hbs');

Then in the route for a particular page the helper is defined the same way the title or an array of data would be:

res.render('editSite', {
      title: 'Update Existing Site\'s Data', siteVars: siteVars, helpers: {
            foo: function () { return console.log('test'); }
        }
    });


回答2:

You need to actually return a string from your helpers. console.log() returns undefined. Try this instead:

hbs.registerHelper("log", function(something) {
  console.log(something);
  return ''+something;
});

hbs.registerHelper('test', function() { 
  console.log('test');
  return 'test';
});


回答3:

in my view, the simpliest way to do what you want, if this is about global helpers (may not be the best solution, but...), is to create your helpers file :

module.exports = {
    customif: (options)=>{
        return (options.hash.expected === options.hash.val) ? options.fn(this) : options.inverse(this);
    }
}

Then, require it :

const handlebarsHelpers = require('./helpers/handlebars');

And finally, when you link express to handlebars, you can insert helpers in the object :

app.engine('hbs', handlebars({
    extname: 'hbs',
    defaultLayout: 'layout',
    layoutsDir: __dirname + '/views/layouts/',
    helpers: handlebarsHelpers
}));

And you can use it inside your layout blabla.hbs:

{{#customif expected='foo' val=field}}
    bar
{{/customif}}

Works for me...