Skip to content

Instantly share code, notes, and snippets.

@andrewdanks
Created October 2, 2012 03:47
Show Gist options
  • Save andrewdanks/3816050 to your computer and use it in GitHub Desktop.
Save andrewdanks/3816050 to your computer and use it in GitHub Desktop.
A simple utility function for rendering a sequence of templates in express for node.
/*
A simple utility function for rendering a sequence of templates in express for node.
Usage:
var utils = require('./utils');
utils.renderTemplates(res, ['header', 'about', 'footer'], {title: 'About'});
*/
module.exports.renderTemplates = function(res, templates, params, callback, error_callback) {
// By default we just send the html in the response
if (typeof callback != 'function') {
callback = function(html) {
res.send(200, html);
};
}
if (typeof error_callback != 'function') {
error_callback = console.log;
}
// Recursively render the templates.
var render = function(templates, rendered_html) {
var template_to_render = templates.shift();
// If it's undefined, we're finished.
if (typeof template_to_render == 'undefined') {
callback(rendered_html);
} else {
// Otherwise we have more work to do.
res.render(template_to_render, params, function(err, html) {
if (err && typeof error_callback == 'function') {
error_callback(err);
}
render(templates, rendered_html + html);
});
}
}
// Let the rendering begin.
render(templates, '', callback);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment