Skip to content

Commit

Permalink
Async templates
Browse files Browse the repository at this point in the history
  • Loading branch information
bpierre committed May 3, 2012
1 parent 2143170 commit b541b81
Showing 1 changed file with 27 additions and 16 deletions.
43 changes: 27 additions & 16 deletions lib/template.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
var _ = require('underscore'),
async = require('async'),
fs = require('fs'),
ejs = require('ejs'),
DEFAULT_SETTINGS = {
Expand All @@ -8,33 +9,43 @@ var _ = require('underscore'),
},
settings;

function loadFile(tplname, opts) {
var tpl = settings.root + '/' + tplname + '.html';
return fs.readFileSync(tpl, 'utf8');
}

function init(opts) {
settings = _.extend({}, DEFAULT_SETTINGS, opts);
}

function render(template, opts, cb) {
function render(template, opts, renderCallback) {
var body,
tpl = loadFile(template);
tpl,
loaders;
opts = _.extend({}, settings, opts);
loaders = [
function(cb) {
fs.readFile(settings.root + '/' + template + '.html', 'utf8', cb);
},
function(cb) {
fs.readFile(settings.root + '/global.json', 'utf8', cb);
}
];

if (opts.layout) {
loaders.push(function(cb) {
fs.readFile(settings.root + '/' + opts.layout + '.html', 'utf8', cb);
});
}

// Globals
fs.readFile(settings.root + '/global.json', 'utf8', function(err, data) {
async.parallel(loaders, function(err, results){
if (!err) {
opts = _.extend({}, opts, JSON.parse(data));
opts = _.extend({}, opts, JSON.parse(results[1]));
}
opts = _.extend({}, settings, opts);
body = ejs.render(results[0], opts);

body = ejs.render(tpl, opts);
if (opts.layout) {
tpl = loadFile(opts.layout);
// Layout
if (loaders.length === 3) {
opts.body = body;
body = ejs.render(tpl, opts);
body = ejs.render(results[2], opts);
}
return cb(body);

return renderCallback(body);
});
}

Expand Down

0 comments on commit b541b81

Please sign in to comment.