9hqcow
Last Updated: February 25, 2016
·
2.658K
· wnstn
E55b7e68e62c19b4801fd04d3f100136

Express 3.0 Layouts with Jade

This took me a good bit of googling so I thought I'd put it here for reference. If you're using Express.js 3.0 with Jade as a templating language, there is no longer a concept of "layouts" - wherein you define some global html layout and then render your content within that layout.

That would have looked something like this:

app.js

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');

app.get("/", function(req, res) {
  res.render('index');
});

And then in /views you'd have layout.jade

!!! 5

body
  #wrapper != body

and index.jade

h1 "hello, world"

That's how I'm used to things working, coming from a Ruby world. But with Express.js 3.0 and the latest version of Jade (0.31, I think?), this does nothing. What you want instead are blocks. Your app.js remains the same, but your views change. Here's how it works:

layout.jade

!!! 5

body

#wrapper
  block content

index.jade

extends layout

h1 "hello, world"

All of this is necessary because in Express.js 3.0, the concept of "layouts" in view rendering was removed by the authors, so you need to move your layout logic to the views themselves.

Say Thanks
Respond

2 Responses
Add your response

8640
0ddfd4bb9279d9b9e6d3ae82badf2cbf

worth mentionning that this isn't particularly new as a feature. You can find the same block logic in twig for instance

over 1 year ago ·
8724
E55b7e68e62c19b4801fd04d3f100136

@tkrugg,

This tip wasn't really about "hey cool, new feature" and more I could not find anyone anywhere explaining the transition, so when I was searching for "jade template layout views with express.js" or whatnot, I was getting outdated advice, and the docs weren't helping either because they are so sparse as to not exist.

over 1 year ago ·