TypeError: Handlebars.registerHelper is not a function

后端 未结 3 716
自闭症患者
自闭症患者 2021-02-02 03:59

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 g

3条回答
  •  粉色の甜心
    2021-02-02 05:04

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

提交回复
热议问题