TypeError: Handlebars.registerHelper is not a function

本秂侑毒 提交于 2019-12-03 08:51:54

问题


I am brand new to node and handlebars as of two days ago so bear with me. I am trying to use custom handlebars helpers but am not entirely sure where to put it.

I keep getting "TypeError: Handlebars.registerHelper is not a function"

Right now I have it in my server.js file. Not sure if this is correct.

var express  = require('express');
var app      = express();
var Handlebars  = require('express-handlebars');


app.engine('handlebars', Handlebars({
    defaultLayout: 'main'
}));

app.set('view engine', 'handlebars');

Handlebars.registerHelper("if", function(conditional, options) {
  if (options.hash.desired === options.hash.type) {
    options.fn(this);
  } else {
    options.inverse(this);
  }
});

回答1:


It looks like you need to use it like this, according to the docs found here: https://github.com/ericf/express-handlebars

var hbs = Handlebars.create({
  // Specify helpers which are only registered on this instance.
  helpers: {
    foo: function () { return 'FOO!'; },
    bar: function () { return 'BAR!'; }
  }
});



回答2:


R.A. Lucas is correct.

The object you get from require('express-handlebars') is not any 'plain old handlebars object'. It's a different object only used in express-handlebars

What you do is pass your helpers (and other settings as well) to the .create() function of that object.

Here's a fully functional example where I define 2 helpers in express-handlebars

var express = require('express');
var exphbs = require('express-handlebars');
var app = express();

//Here you can pass helpers that you would normally define in registerHelpers
//and you can also define stuff like `defaultLayout` and `partialsDir`
var hbs = exphbs.create({
    helpers: {
        sayHello: function () { alert("Hello World") },
        getStringifiedJson: function (value) {
            return JSON.stringify(value);
        }
    },
    defaultLayout: 'main',
    partialsDir: ['views/partials/']
});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
app.set('views', path.join(__dirname, 'views'));



回答3:


Just came across the same problem. Thanks to R.A.Lucas and Drkawashima, the answers above are correct, but here's a slightly shorter option.

var express = require('express');
var handlebars = require('express-handlebars');    
var app = express();

app.engine('handlebars', handlebars({
    helpers: {
        sayHello: function () { return "Hello"; },
        getStringifiedJson: function (value) {
            return JSON.stringify(value);
        }
    },
partialsDir: ['views/partials/'],
defaultLayout: 'main'
}));
app.set('view engine', 'handlebars');


来源:https://stackoverflow.com/questions/33979051/typeerror-handlebars-registerhelper-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!