JamesOR
JamesOR

Reputation: 1168

How do you dynamically set a layout for a Jade template to extend in Node.js/Express 3.0?

I have 3 files: layoutA.jade, layoutB.jade and index.jade. How can I programmatically set which layout that index.jade will extend?

I've tried using:

app.set('view options', { layout: false });

with:

res.render('index', { title: 'Express', layout: 'layoutB' });  // older 2.x way?

I can't seem to override anything set explicitly in the index.jade file. Omitting the extends line inside the index.jade file didn't work either.

Upvotes: 8

Views: 2453

Answers (1)

Jim Buck
Jim Buck

Reputation: 2444

Lets say the jade files are in the following directory:

+ views
  + shared
    - layoutA.jade
    - layoutB.jade
  + home
    - index.jade

Add the layout settings in the correct order, and specify the root views folder:

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('view options', { layout: 'shared/layoutA' });

Make sure you specify the correct folder(in this case 'views'). Also make sure to specify a valid default layout. Check that this works with a test page before you dive deeper.

Once that is working you can the default layout like this:

if(someImportantVar) {
  res.render('home/index', { title: 'Different layout!', layout: 'shared/layoutB' });
} else {
  res.render('home/index', { title: 'Default layout!'});
}

Upvotes: 6

Related Questions