How to include a file in a Jade template which might not be here

I had the problem that I had to include a Jade template from the filesystem which was optional: if it’s here, use it, otherwise just ignore it.

Jade does neither allow conditional includes nor includes of non existing files. The solution for my problem was rendering the file in the code and passing the HTML to the template:

In the node file, I had to add the following code:

var fs = require('fs');
var jade = require('jade');
...
try {
 // If the file is not here, the next line crashes (throws an exception)
 var info = fs.statSync(aboutFile);
 settings.custom.aboutHtml = jade.renderFile(aboutFile, {});
}
catch (e) {
 // don't care. In this case we simply do not have a custom file
}

If the file aboutFile is not available, fs.statSync throws an exception and settings.custom.aboutHtml is not defined. Pass this variable to the rendering engine afterwards:

router.get('/', function (req, res) {
  res.render('index', {title: settings.custom.title, custom: settings.custom});
});

In the Jade template, the rendered HTML is added like this:

if custom.aboutHtml
  // Custom Info Dialog
  !{custom.aboutHtml}
else
  ...

See the complete code in my ZigBee Site Survey project on GitHub: index.js and about.jade.