Tom Maton
Tom Maton

Reputation: 1594

Node.js+Handlebars+Express how to reference the handlebars templates?

I'm relative new to Node & Express, but handlebars templates I've never used before and trying to reference them in my node app.js but I keep on getting the following error

Property 'engine' of object # is not a function

This is my code:

app.configure(function () {
        app.set('views', __dirname+ '/views');
        app.set('port', 3000);
        app.set('view engine', 'handlebars');
        app.use(handlebarsLayout);
        app.use(express.static(path.join(__dirname, 'public')));
        app.use(app.router);
    });

    // ROUTES
    app.get('/', function (req, res){ 
        var data = {
            title: "Node + Handlebars",
            body: "Hello World!"
        }

        res.render('index', data);
    });

    http.createServer(app).listen(app.get('port'), function () {
        console.log("Express server listening on port " + app.get('port'));
    });

Any help would be greatly appreciated.

Thanks, Tom

Upvotes: 1

Views: 8086

Answers (2)

GHETTO.CHiLD
GHETTO.CHiLD

Reputation: 3416

you need to pass your directories for templates and helpers to the app. declare your js at the top.

var helpers = require('./private/js/myhelpers');

then in your app.configure:

// configure express
app.configure(function() {
     //handlebars implementation
     app.set('views', __dirname + '/views');
     app.set('view engine', 'handlebars');
     //handlebars helpers are registered in app.engine, helpers is our hbs.js file
     app.engine('handlebars', exphbs({defaultLayout: 'main', helpers: helpers}));
 ...
 });

Upvotes: 0

Tom Maton
Tom Maton

Reputation: 1594

For anyone interested I found this post very useful and helped solve my issue.

https://stackoverflow.com/a/14346094/911553

I installed consolidate (npm install consolidate) and did the following:

var engines = require('consolidate')

app.configure(function () {
        app.set('views', __dirname+ '/views');
        app.set('port', AppConfig.AppConfig.Express.PORT);

        app.set('view engine', 'html');
        app.set("view options", { layout: true });
        app.engine('.html', engines.handlebars);
        app.use(app.router);
    });

// ROUTES
    app.get('/', function (req, res){ 
        var data = {
            title: "Node + Handlebars",
            body: "Hello World!"
        }

        res.render('index', data);
    });    

and now my pages render with handlebars templates.

Upvotes: 6

Related Questions