How can I include/extend a jade file from the root of my template directory in express?

Problem

Given a sample structure:

/layout.jade
/really/deep/dir/inside/my/template/folder/example.jade

Is there any way I can extend layout.jade in example.jade without having to keep track of the number of parent directories?

This works as intended tho:

extends ../../../..etc../../../layout

But it would be preferable to do something like:

extends /layout

Or even alias/hardlink and use it like:

extends layout

Also assuming somebody knows a solution, can it also be applied to include?

Problem courtesy of: Alex Tzo

Solution

There is a change that was introduced in this particular commit.

Basically, if the first character found in the include statement is a forward slash and basedir is defined, it will look for the template in that path.

You must first setup Jade:

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.locals.basedir = app.get('views');

Then, from any template, no matter how deeply nested, you can do:

include /layout
Solution courtesy of: Pier-Luc Gendreau

Discussion

After taking a look at the code itself, I realized that someone can't simply reference a jade file relevant to the templates root.

However, a simple approach is to patch jade/lib/parser.js replacing two instances of:

, dir = dirname(this.filename);

With:

, dir = path.indexOf('/') ? dirname(this.filename) : this.options.settings.views;

I might as well warn you that this is not tested enough and is not intended for production use.

Discussion courtesy of: Alex Tzo

This recipe can be found in it's original form on Stack Over Flow.