ericf / express-handlebars

A Handlebars view engine for Express which doesn't suck.
BSD 3-Clause "New" or "Revised" License
2.32k stars 382 forks source link

Render with non-default layout and context? #220

Closed ericman314 closed 6 years ago

ericman314 commented 6 years ago

I cannot figure out how to call render() with both a non-default layout and a context. I can do one or the other:

server.js:

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

app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');

app.get('/page1', function(req, res) {
  res.context = {message: "Hello from page1"};
  res.render('../views/index.handlebars', res.context);
});

app.get('/page2', function(req, res) {
  res.render('../views/index.handlebars', {layout: "alternate"});
});

app.get('/page3', function(req, res) {
  res.context = {message: "Hello from page3"};
  res.render('../views/index.handlebars', res.context, {layout: "alternate"});
});

app.listen(3000);

views/index.handlebars:

The message is {{message}}

views/layouts/main.handlebars:

This is the main layout. {{{body}}}

views/layouts/alternate.handlebars:

This is the alternate layout. {{{body}}}

Results

$ curl localhost:3000/page1
This is the main layout. Your message is: Hello from page1

$ curl localhost:3000/page2
This is the alterate layout. Your message is:

$ curl localhost:3000/page3
curl: (52) Empty reply from server

The last request fails with TypeError: callback is not a function at lib/utils.js:26.

What am I doing wrong?

ericman314 commented 6 years ago

This worked:

app.get('/page3', function(req, res) {
  res.context = {
    message: "Hello from page3",
    layout: "alternate"
  };
  res.render('../views/index.handlebars', res.context);
});

Edit: The reason I'm using res.context is that in my application I have some middleware attached which adds some common data to each page via res.context. I guess that you could use an ordinary object as the second argument to render.