Using layouts with jade in express.js
Recently I've been working on a side project[^1] of mine and decided to make use of the jade template engine[^2]. Jade provides nice syntax abstraction over HTML and is the default template engine for express.js[1].
Previous versions of jade/express allowed for automatically loading a layout file for all templates you render. It was possible to deactivate this behaviour by setting view options
on your express app:
app.set('view options', {
layout: false
});
More recent versions of express do not support this anymore. However, jade is a powerful template language and allows extending other templates and defining blocks. This is exactly how you can define a default layout and use it in other templates.
//- layout.jade
doctype html
html
head
block title
title The title
link(href='/css/main.css', rel='stylesheet', type='text/css')
body
#content
block content
block footer
footer
span Copyright %year%
Note that we have defined three blocks here. There is a block called title
that can be used to change the title based on context and has a default title. The content
and footer
blocks can be used to define the main content and an optional footer.
Here is how to use the layout and those blocks in your other templates:
//- posts.jade
extends ./layout
block title
title Post listing
block content
h1 Posts
p Here's a list of all blog posts
extends
and block
are very powerful features of jade and can be used to build extremely complex hierarchies of templates. Enjoy!