Dynamic includes in Jade/ExpressJS

Today I came across a requirement to include a dynamic pre-rendered partial into a Jade template. What I needed was a method to render an array of objects using an object-specific template. Something like that:

- var partial = "../partials/partial" 
for expertise in expertises
	div
		include !{partial}

That doesn’t work. Partials and dynamic includes are currently not supported by Jade for a simple reason that rendering takes place at compile time.
All solutions I came across didn’t work for me. The workaround is surprisingly simple: pre-render the partials and pass them to the main Jade template as a regular variable.
I omit the error handling, all validations and other fun stuff for the sake of clarity:

In the Jade main template:

for expertise in expertises
	div
		!{expertise}

Please note that you would need to use !{expertise} instead of #{expertise} to instruct Jade to output unencoded escaped html.

In the Express controller:

 
// Some logic that returns an array of objects called resolved.expertises that contain objects we want to render depending on their properties
// Declarations
var expertises = [], // will contain rendered html
    data, // will contain local variables for the renderer
    html, // rendered object
    template, // path to the template per object 
    exists = false; // sync file exists validation
 
resolved.expertises.forEach(function(expertise){
 
	template = path.join(app.get("plugins"), expertise.template, '/views/expertise.jade'); // create path for the object template, we define the plugins property in the main app.js on init.
	exists = fs.existsSync(template); // make sure that the path is valid
 
	if (exists){
		data = {expertise:expertise}; // pass object data 
		html = jade.renderFile(template, data); // render the object and return the html
		expertises.push(html); // add the rendered html to an array variable that we will pass to the main template
	}
});
 
res.render('./vendors/expertises', {
	expertises: expertises,
});

That’s it. Please note that this approach will probably slow down your application to some extent because the partials are not cached! In my case it was acceptable.