Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 949
JamesOR Avatar asked Jun 27 '12 20:06

JamesOR


People also ask

Is Jade template engines can be used with node js?

Jade is a template engine for Node. js. Jade syntax is easy to learn. It uses whitespace and indentation as a part of the syntax.

How do I read a dynamic file in node JS?

const fs = require('fs'); app. get("/", (req, res) => { // To read as a text file, you have to specify the correct // encoding. fs. readFile('./sample.

What is Jade file in node JS?

Jade is a template engine for node. js and the default rendering engine for the Express web framework. It is a new, simplified language that compiles into HTML and is extremely useful for web developers. Jade is designed primarily for server-side templating in node.


1 Answers

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!'});
}
like image 87
Jim Buck Avatar answered Oct 19 '22 21:10

Jim Buck