Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Registering handlebars helpers with node does absolutely nothing

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.

like image 470
Elliot Robert Avatar asked Dec 09 '22 06:12

Elliot Robert


1 Answers

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'); }
        }
    });
like image 142
Elliot Robert Avatar answered Dec 11 '22 09:12

Elliot Robert