Skip to content

Instantly share code, notes, and snippets.

@rgrove
Created March 1, 2011 21:57
Show Gist options
  • Save rgrove/849967 to your computer and use it in GitHub Desktop.
Save rgrove/849967 to your computer and use it in GitHub Desktop.
var fs = require('fs'),
fsPath = require('path'),
http = require('http'),
dust = require('dust'),
util = require('./util'), // Our util, not Node's util.
baseContext = dust.makeBase(util.merge(
require('../conf/common'),
require('./helpers')
));
// Loads the named template the first time it's used (it will be cached for
// later calls).
function getView(name, callback) {
name = name.replace(/\.dust$/, '') + '.dust';
fs.readFile(fsPath.join(process.cwd(), 'views', name), 'utf8', callback);
}
dust.onLoad = getView;
// Disable whitespace compression.
dust.optimizers.format = function (context, node) {
return node;
};
// Duckpunch Express's res.render() method to use Dust. This is necessary
// because Express doesn't support async template engines by default.
http.ServerResponse.prototype.render = function (view, options, callback) {
var res = this;
// Support callback as second arg.
if (typeof options === 'function') {
callback = options;
options = {};
}
callback || (callback = function (err, html) {
if (err) { res.req.next(err); return; }
res.send(html);
});
options = options ? baseContext.push(options) : baseContext;
if (res.locals) {
options = options.push(res.locals);
}
// TODO: Figure out a good way to catch parser errors. Currently Dust's
// parser just throws them instead of passing them to the callback.
// See https://github.com/akdubya/dustjs/issues#issue/12
if (res.app.settings.env === 'development') {
dust.cache = {}; // Reflect template changes without a restart.
getView(view, function (err, content) {
if (err) { res.req.next(err); return; }
dust.renderSource(content, options, callback);
});
} else {
dust.render(view, options, callback);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment